Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Exception Handling 1 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Reading Chapter13 2 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Motivation When a program runs into a runtime error, the program terminates abnormally How H can you hhandle dl th the runtime ti error so that th t th the program can continue to run or terminate gracefully? Have you seen errors that were not handled (e.g., FileNotFoundException)? 3 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Objectives Understand exceptions and exception handling (§13.2). Explore the advantages of using exception handling (§13.3). Distinguish exception types: Error (fatal) vs. Exception (nonfatal), and checked vs. unchecked (§13.4). Understand exception programming(§13.5-13.6). Separate regular programming from exception programming (§13.7). Advanced Ad d exception ti programming i (§13 (§13.8-13.10). 8 13 10) 4 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Example What is the best way to handle errors? Consider this program which might fail package lectures; import p j java.util.Scanner; ; public class Quotient { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter 2 integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); System.out.println(number1 + " / " + number2 b 2 + " i is " + ( (number1 b 1 / number2))); b 2))) } run: } 5 Enter 2 integers: 3 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at lectures.Quotient.main(Quotient.java:12) (c) 2011 Pearson Education, Inc.& Robert F. Kelly Exception Handling Advantages Separates the detection of an error from the handing of an error Makes M k code d more readable d bl (i.e., (i maintainable) i t i bl ) Method can just report an error and then request that the calling method handle the error (makes code more reusable) 6 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Example slide Notice that the Java API includes classes whose methods can throw exceptions 7 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Example Consider the exception handling approach package lectures; import java java.util.Scanner; util Scanner; import java.io.*; public class FileNotFoundExceptionDemo { public static void main(String[] args) { Scanner inputFromConsole = new Scanner(System.in); System.out.print("Enter a file name: "); String fileName = inputFromConsole.nextLine(); try { Scanner inputFromFile = new e Scanner(new ca e ( e File(fileName)); e( e a e)); System.out.println( "File " + fileName + " exists"); } catch (FileNotFoundException ex) { System.out.println("Exception: " + fileName + " not found"); }}} 8 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Example – Better Approach Your exception handler can correct the error, as in try { Scanner inputFromFile = new Scanner(new File(fileName)); System.out.println("File " + fileName + " exists"); } catch (FileNotFoundException ex) { System.out.println( "Exception: " + fileName + " not found"); System.out.println("Please reenter file name"); fileName = inputFromConsole.nextLine(); } 9 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Exception Categories Exceptions are objects (check out the Java API) Exception categories SSystem errors – internal i l system errors ((rarely l encountered) d) Examples – LinkageError and VirtualMachineError Exceptions – errors that can be caught and handled by your program Runtime exceptions – programming errors (e.g., out-of-bounds reference to an array, divide an integer by 0) 10 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Exceptions Exceptions - can be caught and handled by your program RuntimeException – caused by programming errors ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object IllegalArgumentException Throwable Many more classes LinkageError Error VirtualMachineError Many more classes Error - thrown by JVM, and not much you can do about them 11 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Notes on Exception Hierarchy Names are a bit confusing – Error, Exception, and RuntimeException are all exceptions – and all occur at runtime Throwable class is the root of exception classes Create your own Exception by extending Exception (or one of its subclasses) No exception for integer overflow 12 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Checked Exception If you did not handle the FileNotFound exception, the Java compiler would object (and maybe suggest options) 13 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Checked vs. Unchecked Exceptions Checked means that the compiler forces you to deal with the exceptions (either handle the exception or re-throw it) RuntimeException R ti E ti - Error E andd their th i subclasses bl are kknown as unchecked exceptions Programming errors that are mostly unrecoverable If they were checked, programs would be overwhelmed with try/catch blocks 14 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable Examples NullPointerException - you access a null object IndexOutOfBoundsException - you access an element in an array outside the bounds of the array ArithmeticException – e.g., divide an integer by zero Logic errors that should be corrected in the program To avoid overuse of try-catch blocks, Java does not mandate code to catch unchecked exceptions 15 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Exception Operations Declaring Throwing Catching public void myMethod() throws IOException, MyException {... ... throw new MyException(); try {...} catch(Exception e){ e){...} } 16 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Declaring Exceptions Every method must state the types of checked exceptions it might throw (declaring exceptions) No N requirement i t tto ddeclare l unchecked h k d exceptions ti public void myMethod() throws IOException {...} public void myMethod() throws IOException, OtherException {...} Multiple exceptions Throws keyword indicates that myMethod might throw an IOException 17 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Creating Exception Classes You can create your own exception class by: Deriving it from Exception Deriving D i i it ffrom a child hild off E Exception ti package progex.chapter13; public class IllegalTriangleException extends Exception { public IllegalTriangleException() { } public IllegalTriangleException(String gripe) { super(gripe); } } 18 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Throwing Exceptions When a program detects an error, the program can create an instance of an appropriate exception type and throw it (throwing an exception) Example throw new TheException(); or throw new TheException(“this TheException( this is a message”); message ); Exceptions have two constructors – a zero parameter constructor and one with a “message” 19 Your handler will frequently extract the message from the exception (c) 2011 Pearson Education, Inc.& Robert F. Kelly Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if ( (newRadius R di > >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); } Older programming languages used awkward constructs (e.g., parameters and return values) to indicate errors 20 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Catching Exceptions To catch and handle an exception, use a try/catch block Syntax If no exceptions are thrown, the catch bl k is block i skipped ki d try { statements; // may throw exceptions } catch (Exception1 exVar1) { handler for exception1 Order of catch blocks is } important – i.e., subtypes first ... catch (ExceptionN exVarN) { handler for exceptionN } If a statement in the try block throws an exception, the remaining statements in the try block are skipped 21 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Catching Exceptions You will see this in a stack trace The exception (if not immediately handled) is propagated backward through the chain of method calls main method { ... try { ... invoke method1; statement1; } catch (Exception1 ex1) { Process ex1; } statement2; } method1 { ... try { ... invoke method2; statement3; } catch (Exception2 ex2) { Process ex2; } statement4; } method2 { ... try { ... invoke method3; statement5; } catch (Exception3 ex3) { Process ex3; } statement6; } Call Stack method3 main method 22 method2 method2 method1 method1 method1 main method main method main method (c) 2011 Pearson Education, Inc.& Robert F. Kelly An exception is thrown in method3 Notes on Catching Exceptions Use a superclass to catch sub-class exceptions Example Catch (Exception e) {} will catch an IOException When listing multiple catches, list the more specific catches last (e.g., catch Exception last) 23 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Deal With Checked Exceptions Java forces you to deal with checked exceptions You must invoke it in a try-catch block or declare to throw the exception th ti in i th the calling lli method th d Example - method p1 invokes method p2, and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b). void p1() { try { p2(); p (); } catch (IOException ex) { ... } } (a) 24 void p1() throws IOException p2(); } (c) 2011 Pearson Education, Inc.& Robert F. Kelly (b) Getting Exception Information Throwable class contains helpful methods getMessage – returns the exception message toString t St i – concatenates t t the th full f ll name off th the exception ti class l andd the exception message getStackTrace – returns an array of stack trace elements printStackTrace – prints the exception object and its call stack trace to the console 25 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Example Main calls method1, which propagates an exception back to main Consider throwing and exception to a calling method public class ExampleStackTrace { public static void main(String[] args) { Scanner inputFromConsole = new Scanner(System.in); System.out.print("Enter a file name: "); String fileName = inputFromConsole.nextLine(); try { method1(fileName); System.out.println("File " + fileName + " exists"); } catch (FileNotFoundException ex) { System.out.println("Exception: " + fileName+" not found"); ex.printStackTrace(); } } public static void method1(String fileName) throws FileNotFoundException { Scanner inputFromFile = new Scanner(new File(fileName));}} 26 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Example The stack trace generated by the handler is run: Enter a file name: test Exception: test not found java.io.FileNotFoundException: test (Access is denied) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:106) at java.util.Scanner.<init>(Scanner.java:636) at lectures.ExampleStackTrace.method1(ExampleStackTrace.java:22) at lectures.ExampleStackTrace.main(ExampleStackTrace.java:13) BUILD SUCCESSFUL ( (total time: 4 seconds) ) 27 (c) 2011 Pearson Education, Inc.& Robert F. Kelly The finally Clause Use a finally clause to execute code whether or not an exception is thrown try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } 28 finallyy block executes even if there is a return statement prior to reaching the finally block (c) 2011 Pearson Education, Inc.& Robert F. Kelly Rethrowing Exceptions An exception handler can re-throw an exception try { statements; } catch(TheException ex) { perform operations before exits; throw ex; } 29 (c) 2011 Pearson Education, Inc.& Robert F. Kelly animation Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; 30 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Suppose no exceptions in the statements, catch block is not executed and … animation Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } The final block is always executed Next statement; 31 (c) 2011 Pearson Education, Inc.& Robert F. Kelly animation Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement in the method is executed Next statement; 32 (c) 2011 Pearson Education, Inc.& Robert F. Kelly animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { ; finalStatements; } Suppose an exception of type Exception1 is thrown in statement2, statement3 is not executed and … Next statement; 33 (c) 2011 Pearson Education, Inc.& Robert F. Kelly animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { ; finalStatements; } Next statement; 34 (c) 2011 Pearson Education, Inc.& Robert F. Kelly The exception is handled. animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { ; finalStatements; } The final block is always executed. Next statement; 35 (c) 2011 Pearson Education, Inc.& Robert F. Kelly animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { ; finalStatements; } Next statement; 36 (c) 2011 Pearson Education, Inc.& Robert F. Kelly The next statement in the method is now executed. animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Exception1 is not a parent class of Exception2 statement2 throws an exception of type Exception2. Exception1 handler is not executed, and … Next statement; 37 (c) 2011 Pearson Education, Inc.& Robert F. Kelly animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Handling exception Next statement; 38 (c) 2011 Pearson Education, Inc.& Robert F. Kelly animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Execute the final block Next statement; 39 (c) 2011 Pearson Education, Inc.& Robert F. Kelly animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; 40 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Rethrow the exception and control is transferred to the caller Cautions When Using Exceptions Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object rolling back the call stack p propagating p g g the errors to the callingg methods. 41 (c) 2011 Pearson Education, Inc.& Robert F. Kelly When to Throw Exceptions An exception occurs in a method If you want the exception to be processed by its caller, you should h ld create t an exception ti object bj t andd throw th it If you can handle the exception in the method where it occurs, there is no need to throw it 42 (c) 2011 Pearson Education, Inc.& Robert F. Kelly When to Use Exceptions Unexpected situations Example – correct, but not good style try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); } Example – correct, better style if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null"); 43 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Defining Custom Exception Classes Use the exception classes in the API whenever possible. Define custom exception classes if the predefined classes are nott sufficient. ffi i t Define custom exception classes by extending Exception or a subclass of Exception. 44 (c) 2011 Pearson Education, Inc.& Robert F. Kelly Have You Satisfied Objectives? Understand exceptions and exception handling (§13.2). Explore the advantages of using exception handling (§13.3). Distinguish exception types: Error (fatal) vs. Exception (nonfatal), and checked vs. unchecked (§13.4). Understand exception programming(§13.5-13.6). Separate regular programming from exception programming (§13.7). Advanced Ad d exception ti programming i (§13 (§13.8-13.10). 8 13 10) 45 (c) 2011 Pearson Education, Inc.& Robert F. Kelly