Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP201 Java Programming Topic 7: Exceptions Reading: Chapter 11.

Similar presentations


Presentation on theme: "COMP201 Java Programming Topic 7: Exceptions Reading: Chapter 11."— Presentation transcript:

1 COMP201 Java Programming Topic 7: Exceptions Reading: Chapter 11

2 COMP201 Topic 7 / Slide 2 Outline l Introduction l Java exception classes l Dealing with exceptions  Throwing exceptions  Catching exceptions

3 COMP201 Topic 7 / Slide 3 Introduction l Causes of errors l User input errors: typos, malformed URL, wrong file name, wrong info in file… l Hardware errors: Disk full, printer out of paper or down, web page unavailable… l Code errors: invalid array index, bad cast, read past end of file, pop empty stack, null object reference…

4 COMP201 Topic 7 / Slide 4 Introduction l Goals of error handling l Don’t want: l Want: l Return to a safe state and enable user to execute other commands l Allow user to save work and terminate program gracefully.

5 COMP201 Topic 7 / Slide 5 Introduction l Java exception handling mechanism: Every method is allowed to have two exit paths n No errors occur –Method exits in the normal way –Returns a value –Control passed to the calling code. n If errors occur –Method exits via an alternative exit path –Throws an object that encapsulates the error information –Control passed to exception mechanism that searches for an appropriate exception handler to deal with the error condition

6 COMP201 Topic 7 / Slide 6 Throw & Catch an Exception l Exception object is created when an error occurs l Exception object contains information about the exception l The object is handed off to the runtime system l Runtime system searches for the method that contains an appropriate exception handler

7 COMP201 Topic 7 / Slide 7 Advantage l Separate error handling code from regular code n Sample code without error handling n traditional error detection, reporting, and handling often lead to messy code readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; }

8 Traditional Approach errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; } Java Exception Handling Approach readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } It does NOT spare your effort to detect, report and handle the exception, but provide an elegant framework.

9 COMP201 Topic 7 / Slide 9 Java Exception Class JVM internal errors

10 COMP201 Topic 7 / Slide 10 Java Exception Classes l Java has many classes for error handling. They are called exception classes java.io.IOException java.lang.VirtualMachineError java.lang.LinkageError java.lang. Exception java.lang. Error java.lang. Throwable java.lang.NullPointerException java.lang.ArithmeticException java.lang.RuntimeException java.lang.ClassCastException unchecked checked java.io.EOFException …

11 COMP201 Topic 7 / Slide 11 Unchecked exceptions Error : For internal errors in JVM. RuntimeException : Logical errors in program (C++ logical-error).  Bad cast  Out-of-bound array access  Null reference access l Those two exceptions are unchecked  JVM internal errors beyond your control  You should not allow logical errors at the first place

12 COMP201 Topic 7 / Slide 12 l All other exceptions (C++ runtime_error) are checked, i.e. you have to explicitly handle them. Otherwise compiler errors results in. n Trying to read pass end of file n Open a malform URL n … AclNotFoundException, ActivationException, AWTException, BadLocationException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, ExpandVetoException, GeneralSecurityException, IllegalAccessException, InstantiationException, InterruptedException, IntrospectionException, InvocationTargetException, IOException, LastOwnerException, … Checked exceptions Can be found in online API

13 COMP201 Topic 7 / Slide 13 Java Exception Classes l You can define new Exception classes. class FileFormatException extends IOException { // default constructor public FileFormatException() {} //constructor contains a detailed message public FileFormatException(String message) { super( message ); } New Exception class must be subclass of Throwable Most programs throw and catch objects that derive from the Exception class

14 COMP201 Topic 7 / Slide 14 Dealing with Exceptions l Need to consider exceptions when writing each method l Identifying possible exceptions n Check the API of each method you use to see if it throws an exceptions n Consider whether your own codes might produce exceptions. l Dealing with exceptions n Catching exceptions: Do this if you know how to handle an exception in the current method. n Throwing exceptions: Do this if you don’t know how to handle an exception in the current method and need the caller method to deal with it. The most important slide

15 COMP201 Topic 7 / Slide 15 Example: Consider reading Employee information from a text file: File format ( employeeGood.dat ) 3 Harry Hacker|37363.75|1989|10|1 Carl Cracker|78937.5|1987|12|15 Tony Tester|39995.0|1990|3|15 Some thing might go wrong ( employeeBad.dat ) 3 Harry Hacker|37363.75|1989|10|1 Carl Cracker|78937.5|1987|12|15 Tony Tester|39995.0|1990|3| Throwing Exceptions Missing one item here

16 COMP201 Topic 7 / Slide 16 Throw an exception generated by method call : public void readData(BufferedReader in)throws IOException { String s = in.readLine(); StringTokenizer t = new StringTokenizer(s, "|"); name = t.nextToken(); salary = Double.parseDouble(t.nextToken()); int y = Integer.parseInt(t.nextToken()); int m = Integer.parseInt(t.nextToken()); int d = Integer.parseInt(t.nextToken()); GregorianCalendar calendar = new GregorianCalendar(y, m - 1, d); // GregorianCalendar uses 0 = January hireDay = calendar.getTime(); }// DataFileTest.java Throwing Exceptions

17 COMP201 Topic 7 / Slide 17 The method readLine of BufferedReader throws an IOExpcetion. We do not deal with this exception in the current method. So we state that the readData method might throw IOException. l If you simply ignore it, compiler error results in. Try this. Throwing Exceptions

18 COMP201 Topic 7 / Slide 18 The nextToken method might produce an NoSuchElementException. l But this exception is unchecked, so we don’t have to worry about it. No compiler errors result in because of this. This leads to ungraceful behavior when exception is thrown (Run ReadTextTest2 on employeeBad.dat ) Throwing Exceptions

19 COMP201 Topic 7 / Slide 19 l Create and throw your own exception public void readData(BufferedReader in) throws IOException, FileFormatException { String s = in.readLine(); StringTokenizer t = new StringTokenizer(s, "|"); … int d; if (t.hasMoreTokens()) { d = Integer.parseInt(t.nextToken()); } else { FileFormatException e = new FileFormatException ("Last item missing in:\n" + s +"\n" ); throw e; } … } //ExceptionTest.java Throwing Exceptions

20 COMP201 Topic 7 / Slide 20 l Notes: n Can throw multiple types of exceptions public void readData(BufferedReader in) throws IOException, FileFormatException n Overriding method in subclass cannot throw more exceptions than corresponding method in superclass –If method in superclass does not throw any exceptions, overriding method in subclass cannot either Suppose method1 calls method2. If method2 throws someException, method1 must –Either catch someException –Or declare someException in its header Throwing Exceptions

21 COMP201 Topic 7 / Slide 21 Catching Exceptions Catch exceptions with try/catch block try { code more code } catch( ExceptionType e) { handler for this exception } If a statement in the try block throws an exception l The remaining statements in the block are skipped Handler code inside catch block executed. If no exceptions are thrown by codes in the try block, the catch block is skipped.

22 COMP201 Topic 7 / Slide 22 Catching Exceptions public static void main(String[] args) { try { BufferedReader in = new BufferedReader( new FileReader(args[0])); Employee[] newStaff = readData(in); … } catch(IOException exception) { exception.printStackTrace(); exit(0); }} //ExceptionTest.java This code will exit right away with an error message if something goes wrong in readData or in the constructor of FilerReader (an IOException will be thrown)

23 COMP201 Topic 7 / Slide 23 l An more interesting exception handler public void readData(BufferedReader in) throws IOException { String s = in.readLine(); StringTokenizer t = new StringTokenizer(s, "|"); … int d; try { d = Integer.parseInt(t.nextToken()); } catch (NoSuchElementException e) { String input = JOptionPane.showInputDialog ("Hire day for "+ name +"not available from file.\n“ + "please provide from keyboard"); // convert string to integer value d = Integer.parseInt(input); … }} // ExceptionTest1.java Catching Exceptions

24 COMP201 Topic 7 / Slide 24 Catching Multiple Exceptions Can have multiple catchers for multiple types of exceptions: public static void main(String[] args) { try { BufferedReader in = new BufferedReader( new FileReader(args[0])); Employee[] e = readData(in); … } catch(IOException e1) { exception.printStackTrace(); } catch(ArrayIndexOutOfBoundsException e2) { System.out.print("No file name provided " ); System.exit(1); } } // ExceptionTest2.java Might throw ArrayIndexOutOfBoundsExpection

25 COMP201 Topic 7 / Slide 25 Dealing with Exceptions l Example: try { average = total/count; System.out.println(“Average is ” + average); } catch (ArithmeticException e) { System.out.println(“Oops: ”+ e); average = -1;} If count is 0, this code will print out something like “ Oops: division by zero ”.

26 COMP201 Topic 7 / Slide 26 Dealing with Exceptions l Can have multiple catchers for multiple types of exceptions: try {…} catch (ArithmeticException e1){…} catch (IOException e2) {…} catch (Exception e3) {…} //ANY exception

27 COMP201 Topic 7 / Slide 27 Catching Exceptions l Catchers can also re-throw an exception or throw exception that is different from the exception caught. graphics g = image.getGraphics(); try { …} catch (MalformedURLException e) { g.dispose(); throw e; } We wish to dispose the graphics object g, but we don’t know how to deal with the exception.

28 COMP201 Topic 7 / Slide 28 The finally clause try { code more code} catch( ExceptionType e) { handler for this exception} finally {.. } The finally block is executed regardless whether exceptions are thrown in the try block. l Useful in situations where resources must be released no matter what happened

29 COMP201 Topic 7 / Slide 29 A caution about the finally clause: Codes in the finally block are executed even there are return statements in the try block public static int f(int n) { try { return n* n; } finally { if ( n==2) return 0; } f(2) return 0 instead of 4! The finally clause

30 COMP201 Topic 7 / Slide 30 Dealing with Exceptions l Search for handler: Steps: –Tries to find a handler in the Catch block for the current exception in the current method. Considers a match If the thrown object can legally be assigned to the exception handler’s argument. –If not found, move to the caller of this method –If not there, go another level upward, and so on. (Reason for the last item on slide 20.) –If no handler found, program terminates.

31 COMP201 Topic 7 / Slide 31 C++ Notes l Java exception handling similar to that of C++, except: –C++ enforces the throw specifier at run time, while Java checks Throw specifier at compile time. –In C++ a function can throw an exception in case of no throw specification, while in Java a method can only throw exceptions advertised. –In C++ you can throw values of any type, while in Java you can only throw objects of a subclass of Throwable.


Download ppt "COMP201 Java Programming Topic 7: Exceptions Reading: Chapter 11."

Similar presentations


Ads by Google