LECTURE NOVEMBER 1 2004 ASSIGNMENTS Fri 11/5 CodeLab #9 Mon 11/8 Assignment 3 Code - Questions about Assignment 3? CATCHING EXCEPTIONS What? - reliable program How? - correct results for all valid input - robust: doesn't crash easily even for invalid input What? - *exception* When? - normal course of program execution When? - an exception occurs What? - exception is thrown What? - handling exceptions How? - so far, left to system Example: - AgeInputVer1 Results? - java.lang.NumberFormatException: nine at java.lang.Integer.parseInt(Integer.java:405) at java.lang.Integer.parseInt(Integer.java:454) at AgeInput.getAge(AgeInput.java:46) at Ch8AgeInputMain.main(Ch8AgeInputMain.java:24) What? - exception is caught How? - *exception-handling* routine is executed - syntax try { // block including a statement that could throw an exception } catch ( /* declaration of exception to catch */) { // exception-handling block } - catch clause must declare an exception type and identifier - e.g. Exception e - catch block only catches particular type of exception - e.g. if declared IOException ioe, won't catch NullPointerException - but does catch all children; e.g. Exception will catch IOException What? - control flow When? - exception occurs How? - try block executed through the statement that causes the exception - skips the remainder of the try block - executes the catch block - continues after the try-catch block What? - control flow When? - no exception How? - try block executed completely - catch block skipped - continues after the try-catch block Example: myAgeInputVer2.java MULTIPLE CATCH BLOCKS Why? - code generates more than one type of exception What? - multiple catch blocks How? - syntax: try { } catch () { } catch () { ... } - only one will be executed for a given exception - checked in sequence: the first one that matches is executed - put the most specialized at the top What? - no matching catch statement How? - system handles Example: try { inputStr = bf.readLine(); int age = Integer.parseInt(inputStr); } catch (IOException ioe) { } catch (NumberFormatException nfe) { } RESERVED WORD FINALLY Why? - designate code that must always be executed, whether or not an exception occurs - cleanup code What? - reserved word finally How? - syntax: try { // exception-throwing block } catch ( ) { // catch block } finally { // finally block } Example: finallyEg.java THROWING EXCEPTIONS What? - throwing exceptions How? - syntax: throw ; - - can be any Exception subclass - typically use the most specialized subclass Example: AgeInputVer3.java TYPES OF EXCEPTIONS What? - exception hierarchy How? - Throwable