University of Hail College of Computer Science and Engineering Department of Computer Science and Software Engineering ICS201 Exception Handling Slides prepared by Rose Williams, Binghamton University What is an Exception? Indication of problem during execution Examples – Divide by zero errors – Accessing the elements of an array outside its range – Invalid input – Opening a non-existent file –… Exceptions– a better error handling Exceptions act similar to method return flags in that encounter an error. Exceptions act like global error methods in that the exception mechanism is built into Java Exception Handling in Java 3 Exception Example class DivByZero { public static void main(String args[]) { System.out.println(3/0); System.out.println(" Pls. print me. "); } } Displays this error message Exception in thread "main" java.lang.ArithmeticException: / by zero at DivByZero.main(DivByZero.java:3) Causes the program to terminate Another Example public class ExceptionExample { public static void main(String args[]) { String[] greek = {"Alpha","Beta"}; System.out.println(greek[2]); } } Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4) Coding Exceptions To handle the exception, you write a “try-catch” block. try { … normal program code } catch(Exception e) { … exception handling code } It prevents the program from automatically terminating Exception Handling in Java 6 Example Output: Division by zero. After catch statement. 7 public class ExceptionExample { public static void main(String args[]) { try{ String[] greek = {"Alpha","Beta"}; System.out.println(greek[2]); } catch(Exception e) { System.out.print ("Index of array out of range"); } } } Catching Multiple Exceptions Handle multiple possible exceptions by multiple successive catch blocks try { // code that might throw multiple exception } catch (IOException e) { // handle IOException and all subclasses } catch (ClassNotFoundException e2) { // handle ClassNotFoundException } Exception Handler Exception "thrown" here Thrown exception matched against first set of exception handlers Exception handler Exception handler If it fails to match, it is matched against next set of handlers, etc. If exception matches none of handlers, program is discarded 10 Exception Classes There are two kinds of exceptions in Java Predefined exception classes in the Java libraries New exception classes can be defined like any other class Exception Classes from Standard Packages Predefined exception classes are included in the standard packages that come with Java ◦ For example: IOException NoSuchMethodException FileNotFoundException ◦ Many exception classes must be imported in order to use them import java.io.IOException; All predefined exception classes have the following properties: ◦ There is a constructor that takes a single argument of type String ◦ The class has an accessor method getMessage that can recover the string given as an argument to the constructor when the exception object was created. Exception Classes from Standard Packages The predefined exception class Exception is the root class for all exceptions ◦ Every exception class is a derived class of the class Exception ◦ Although the Exception class can be used directly in a class or program, it is most often used to define a derived class ◦ The class Exception is in the java.lang package, and so requires no import statement 9-13 A Programmer-Defined Exception Class Types of error: 1. Syntax errors: the rules of the language have not been followed (detected by the compiler). 2. Runtime errors occur while the program is running (detects an operation that is impossible to carry out). 3. Logic errors occur when a program doesn't perform the way it was intended to. 15 Runtime Errors import java.util.Scanner; If an exception occurs on this line, the rest of the lines in the method are skipped and the program is terminated. Terminated. public class ExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextInt(); // Display the result System.out.println( "The number entered is " + number); } } 16 Catch Runtime Errors import java.util.*; public class HandleExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); boolean continueInput = true; do { try { System.out.print("Enter an integer: "); int number = scanner.nextInt(); If an exception occurs on this line, the rest of lines in the try block are skipped and the control is transferred to the catch block. // Display the result System.out.println( "The number entered is " + number); continueInput = false; } catch (InputMismatchException e) System.out.println("Try again. "Incorrect input: an integer scanner.nextLine(); // discard } } while (continueInput); } { (" + is required)"); input 17 Throwing Exceptions When the program detects an error, the program can create an instance of an exception type and throw it. This is known as throwing an exception. 18 Using the throws Clause Appears after method’s parameter list and before the method’s body Contains a comma-separated list of exceptions Exceptions can be thrown by statements in method’s body of by methods called in method’s body Exceptions can be of types listed in throws clause or subclasses 19 Declaring, Throwing, and Catching Exceptions declare exception method1() { method2() throws Exception { try { invoke method2; } catch (Exception ex) { Process exception; } catch exception if (an error occurs) { throw new Exception(); } throw exception } } 20 Declaring Exceptions Every method state the types of checked exceptions it might throw. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException 21 Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); } 22 Sequence of Events for throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step 23 Sequence of Events for No throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step 24 1 // Fig. 13.2: DivideByZeroWithExceptionHandling.java 2 // An exception-handling example that checks for divide-by-zero. 3 import java.util.InputMismatchException; 4 5 6 import java.util.Scanner; 7 8 { 25 public class DivideByZeroWithExceptionHandling // demonstrates throwing an exception when a divide-by-zero occurs 9 10 public static int quotient( int numerator, int denominator ) throws ArithmeticException 11 12 13 14 { 15 16 17 18 public static void main( String args[] ) { Scanner scanner = new Scanner( System.in ); // scanner for input boolean continueLoop = true; // determines if more input is needed 19 20 21 22 23 24 25 return numerator / denominator; // possible division by zero } // end method quotient throws clause specifies that method quotient may throw an ArithmeticException Repetition statement loops until try block completes successfully do { try // read two numbers and calculate quotient try block attempts to read input and perform division { System.out.print( "Please enter an integer numerator: " ); int numerator = scanner.nextInt(); Retrieve input; InputMismatchExcept ion thrown if input not valid integers 26 System.out.print( "Please enter an integer denominator: " ); 27 28 int denominator = scanner.nextInt(); int result = quotient( numerator, denominator ); System.out.printf( "\nResult: %d / %d = %d\n", numerator, 29 30 31 32 33 34 35 36 37 38 39 40 41 Call method quotient, continueLoop = false; // input successful; end looping which may throw If we have reached this point, } // end try ArithmeticException input was valid and catch ( InputMismatchException inputMismatchException ) { denominator was non-zero, System.err.printf( "\nException: %s\n", Catching InputMismatchException so looping can stop inputMismatchException ); (user has entered non-integer input) scanner.nextLine(); // discard input so user can try again Exception parameters System.out.println( Read input "You must enter integers. Please tryinvalid again.\n" ); but do nothing with } // end catch it denominator, result ); 42 catch ( ArithmeticException arithmeticException ) 43 44 { 45 46 47 48 26 Notify user of error Catching ArithmeticException madezero for denominator) (user has entered Please try again.\n" ); System.err.printf( "\nException: %s\n", arithmeticException ); System.out.println( "Zero is an invalid denominator. } // end catch } while ( continueLoop ); // end do...while 49 } // end main 50 } // end class DivideByZeroWithExceptionHandling If line 32 was never successfully reached, loop continues and user can try again The finally Clause try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } This block contains code that is ALWAYS executed, either after the “try” block code, or after the “catch” block code. 27 Sequence of Events for finally clause Preceding step try block throw statement unmatched catch matching catch unmatched catch finally next step 28 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Suppose no exceptions in the statements Next statement; 29 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } The final block is always executed Next statement; 30 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement in the method is executed Next statement; 31 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 Next statement; 32 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } The exception is handled. Next statement; 33 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } The final block is always executed. Next statement; 34