Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.

Similar presentations

Presentation on theme: "Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code."— Presentation transcript:

1 Exception Handling

2 Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code would never have bugs. So far, we have mostly presented code as though we lived in this kind of perfect world. The fact that software modules should be robust enough to work under every situation. The exception handling mechanism is key to achieving this goal.

3 Exception Handling The mission of exception handling is to transfer control from where the error occurred to an error handler that can deal with the situation. To handle exceptional situations in program, it must take into account the errors and problems that may occur.

4 What’s errors? User input errors. ◦ Inevitable typing Device errors ◦ Printer turn off, web page unavailable Physical limitations ◦ Disk can fill up, run out memory Code errors ◦ Invalid index array

5 Exception Terminology Using the exception handling mechanism in Java involves: ◦ identifying exception conditions relevant to the application; ◦ locating exception handlers to respond to potential conditions; and ◦ monitoring when such conditions occur.

6 Exception Terminology As with all representations in Java, exception conditions are denoted by objects. Similar with all objects, exceptions are also defined by class constructs, but inheriting attributes from the Exception superclass. While exception objects may be identified by object tags, additional attributes may be included for custom manipulation.

7 Exception Hirarchy in Java

8 Runtime Exception Exceptions that inherit from RuntimeException include such problems as ◦ A bad cast ◦ An out-of-bounds array access ◦ A null pointer access Exceptions that do not inherit from RuntimeException include ◦ Trying to read past the end of a file ◦ Trying to open a malformed URL ◦ Trying to find a Class object for a string that does not denote an existing class

9 Runtime Exception The rule “If it is a RuntimeException, it was your fault” works pretty well.

10 Exception Terminology Exception handling is dynamically enabled for statement blocks within a try block. Within it, normal facilities and rules for blocks apply but control-flow within may be transferred to associated exception handlers. An appropriate statement block prefixed by a catch-clause is then executed when the associated exception condition occurs.

11 Exception Terminology The occurrence of an exception condition is indicated by a throw- statement. It allows for an exception object to be dynamically propagated to the most recent exception handler. Flow- control does not return following a throw-statement. Instead, execution control proceeds at the statement following the try-block that handles the exception.

12 Constructs and Exception Semantics in Java We now consider the language primitives for realizing the exception handling framework in Java. As seen, ◦ exception objects are defined via class constructs that inherit from the Exception class; ◦ exception handling is enabled within a try-block, with handlers indicated by catch clauses; and ◦ an exception condition is identified by a throw statement. (Some predefined exception conditions are thrown implicitly by the Java Virtual Ma-chine.)

13 Raising Exceptions An exception condition is ultimately represented by an exception object derived from the predefined Exception class. A condition is made known by throwing an appropriate object via a throw statement, to be subsequently caught by an associated handler.

14 Declaring Checked Exception A Java method can throw an exception if it encounters a situation it cannot handle. The idea is simple: a method will not only tell the Java compiler what values it can return, it is also going to tell the compiler what can go wrong.

15 Example Throw Exception public FileInputStream(String name) throws FileNotFoundException

16 Throw Exception An exception is thrown in any of the following four situations: ◦ Program call a method that throws a checked exception, for example, the FileInputStreamconstructor. ◦ Program detect an error and throw a checked exception with the throw statement ◦ You make a programming error, such as a[-1] = 0 that gives rise to an unchecked exception such as an ArrayIndexOutOfBoundsException. ◦ An internal error occurs in the virtual machine or runtime library.

17 Throw Exception class MyAnimation {... public Image loadImage(String s) throws IOException {... }

18 Throw Exception class MyAnimation {... public Image loadImage(String s) throws EOFException, MalformedURLException {... }

19 Throw Exception String readData(Scanner in) throws EOFException {... while (...) { if (!in.hasNext()) // EOF encountered { if (n < len) throw new EOFException(); }... } return s; }

20 How to throw exception Throwing an exception is easy if one of the existing exception classes works. In this case: ◦ Find an appropriate exception class. ◦ Make an object of that class. ◦ Throw it.

21 Defining Exception Objects The smallest exception object in Java merely extends from the Exception superclass,as outlined in the class definition: class FileFormatException extends IOException { public FileFormatException() {} public FileFormatException(String gripe) { super(gripe); }

22 Throw own exception String readData(BufferedReader in) throws FileFormatException {... while (...) { if (ch == -1) // EOF encountered { if (n < len) throw new FileFormatException(); }... } return s; }

23 Defining Exception Handlers Exception handlers are introduced by the catch-clause within a try-block prefix, of which the following code fragment is representative.

24 Example try { code more code } catch (ExceptionType e) { handler for this type } If any of the code inside the try block throws an exception of the class specified in the catch clause, then The program skips the remainder of the code in the try block. The program executes the handler code inside the catch clause.

25 Multiple Catch Exception try { code that might throw exceptions } catch (MalformedURLException e1) { emergency action for malformed URLs } catch (UnknownHostException e2) { emergency action for unknown hosts } catch (IOException e3) { emergency action for all other I/O problems }

26 Access exeption information The exception object (e1, e2, e3) may contain information about the nature of the exception. To find out more about the object to get the detailed error message (if there is one) e3.getMessage() to get the actual type of the exception object. e3.getClass().getName()

Download ppt "Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code."

Similar presentations

Ads by Google