1 Chapter 15 Exception Handling Outline 15 1

  • Slides: 26
Download presentation
1 Chapter 15 – Exception Handling Outline 15. 1 15. 2 15. 3 15.

1 Chapter 15 – Exception Handling Outline 15. 1 15. 2 15. 3 15. 4 15. 5 15. 6 15. 7 15. 8 15. 10 15. 11 Introduction Exception-Handling Overview Exception-Handling Example: Divide by Zero Java Exception Hierarchy Rethrowing an Exception finally Clause Stack Unwinding print. Stack. Trace, get. Stack. Trace and get. Message Declaring New Exception Types Constructors and Exception Handling 2003 Prentice Hall, Inc. All rights reserved.

2 15. 1 Introduction • Exception handling – Exception is an indication of problem

2 15. 1 Introduction • Exception handling – Exception is an indication of problem during execution • “exception” occurs infrequently • e. g. , divide by zero – Promotes robust and fault-tolerant software – Java’s Exception Handling nearly identical to C++ 2003 Prentice Hall, Inc. All rights reserved.

3 15. 2 Exception-Handling Overview • Mixing program code with error-handling code makes program

3 15. 2 Exception-Handling Overview • Mixing program code with error-handling code makes program difficult to read, modify, maintain, debug • Uses of exception handling – Process exceptions from program components – Handle exceptions in a uniform manner in large projects – Remove error-handling code from “main line” of execution • A method detects an error and throws an exception – Exception handler processes the error – Uncaught exceptions yield adverse effects • Might terminate program execution 2003 Prentice Hall, Inc. All rights reserved.

4 15. 2 Exception-Handling Overview • Code that could generate errors put in try

4 15. 2 Exception-Handling Overview • Code that could generate errors put in try blocks – Code for error handling enclosed in a catch clause – The finally clause always executes • Termination model of exception handling – The block in which the exception occurs expires immediately • throws clause specifies exceptions method throws (or by methods it calls) • Simple problems that can easily be fixed can be handled as “errors” • Use Exception Handling for more complicated situations 2003 Prentice Hall, Inc. All rights reserved.

5 15. 2 Exception-Handling Overview • Typical exceptions – array index out of range,

5 15. 2 Exception-Handling Overview • Typical exceptions – array index out of range, overflow, division by zero, invalid method parameters, memory allocation problems • Most significant use of Exception Handling – problem occurs in a method, but resolution must be done in calling method (one or more levels above) • Method that detects problem “throws an exception” • Method that resolves problem “catches the exception” 2003 Prentice Hall, Inc. All rights reserved.

15. 3 Exception-Handling Example: Divide by Zero • Common programming mistake • Throws Arithmetic.

15. 3 Exception-Handling Example: Divide by Zero • Common programming mistake • Throws Arithmetic. Exception • Number. Format. Exception is thrown if parse. Int, parse. Double, etc. are given bad strings • Program catches an exception in an “appropriate” catch block (same class or superclass) • Program continues executing with code after the last catch block (not back inside the try block) 2003 Prentice Hall, Inc. All rights reserved. 6

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 15. 1: Divide. By. Zero. Test. java // An exception-handling example that checks for divide-by-zero. import java. awt. *; import java. awt. event. *; import javax. swing. *; Outline 7 public class Divide. By. Zero. Test extends JFrame implements Action. Listener { private JText. Field input. Field 1, input. Field 2, output. Field; private int number 1, number 2, result; // set up GUI public Divide. By. Zero. Test() { super( "Demonstrating Exceptions" ); // get content pane and set its layout Container container = get. Content. Pane(); container. set. Layout( new Grid. Layout( 3, 2 ) ); Divide. By. Zero. Tes t. java // set up label and input. Field 1 container. add( new JLabel( "Enter numerator ", Swing. Constants. RIGHT ) ); input. Field 1 = new JText. Field(); container. add( input. Field 1 ); 2003 Prentice Hall, Inc. All rights reserved.

27 28 29 30 31 32 33 34 35 36 37 38 39 40

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 // set up label and input. Field 2; register listener container. add( new JLabel( "Enter denominator and press Enter ", Swing. Constants. RIGHT ) ); input. Field 2 = new JText. Field(); container. add( input. Field 2 ); input. Field 2. add. Action. Listener( this ); Outline 8 // set up label and output. Field container. add( new JLabel( "RESULT ", Swing. Constants. RIGHT ) ); output. Field = new JText. Field(); container. add( output. Field ); set. Size( 425, 100 ); set. Visible( true ); } // end Divide. By. Zero. Test constructor // process GUI events public void action. Performed( Action. Event event ) { output. Field. set. Text( "" ); // clear output. Field // read two numbers and calculate quotient try { number 1 = Integer. parse. Int( input. Field 1. get. Text() ); number 2 = Integer. parse. Int( input. Field 2. get. Text() ); Divide. By. Zero. Tes t. java Line 51 The try block Lines 52 -53 Read integers from JText. Fields 2003 Prentice Hall, Inc. All rights reserved.

54 55 56 57 58 59 60 61 62 63 64 65 66 67

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 result = quotient( number 1, number 2 ); output. Field. set. Text( String. value. Of( result ) ); Outline Method quotient attempts division 9 } // process improperly formatted input catch ( Number. Format. Exception number. Format. Exception ) { JOption. Pane. show. Message. Dialog( this, "You must enter two integers", "Invalid Number Format", JOption. Pane. ERROR_MESSAGE ); } // process attempts to divide by zero catch ( Arithmetic. Exception arithmetic. Exception ) { JOption. Pane. show. Message. Dialog( this, arithmetic. Exception. to. String(), "Arithmetic Exception", JOption. Pane. ERROR_MESSAGE ); } } // end method action. Performed // demonstrates throwing an exception when a divide-by-zero occurs public int quotient( int numerator, int denominator ) throws Arithmetic. Exception { return numerator / denominator; } Catch Number. Format. Exception Divide. By. Zero. Tes t. java Catch Arithmetic. Exception Line 55 Line 60 Line 67 Line 77 Method quotient throws Arithmetic. Exception 2003 Prentice Hall, Inc. All rights reserved.

81 82 83 84 85 86 87 88 public static void main( String args[]

81 82 83 84 85 86 87 88 public static void main( String args[] ) { Divide. By. Zero. Test application = new Divide. By. Zero. Test(); application. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE ); } Outline 10 } // end class Divide. By. Zero. Test Divide. By. Zero. Tes t. java 2003 Prentice Hall, Inc. All rights reserved.

11 15. 4 Java Exception Hierarchy • Exceptions (like everything in Java) are objects

11 15. 4 Java Exception Hierarchy • Exceptions (like everything in Java) are objects • Superclass Throwable – Subclass Exception • Exceptional situations • Should be caught by program – Subclass Error • Typically not caught by program • Checked exceptions (include any you create) – “catch or declare” requirement • Unchecked exceptions (subclass of Runtime. Exception, e. g. , Number. Format. Exception) – Good idea to catch, but not required 2003 Prentice Hall, Inc. All rights reserved.

Fig. 15. 2 Inheritance hierarchy for class Throwable Exception Runtime. Exception IOException 2003 Prentice

Fig. 15. 2 Inheritance hierarchy for class Throwable Exception Runtime. Exception IOException 2003 Prentice Hall, Inc. All rights reserved. Error AWTError Thread. Death Out. Of. Memory. Error 12

13 15. 5 Rethrowing an Exception • Rethrow exception if catch cannot handle it

13 15. 5 Rethrowing an Exception • Rethrow exception if catch cannot handle it • This typically involves a try block (with its catch blocks) inside another try block • Inner catch block throws it to the outer catch block … or even on to the calling method 2003 Prentice Hall, Inc. All rights reserved.

14 15. 6 finally Clause • Resource leak – Caused when resources are not

14 15. 6 finally Clause • Resource leak – Caused when resources are not released by a program – files, database connections, network connections • The finally block (optional) – Appears after catch blocks – Always executes whether or not any exception is thrown – Use to release resources (e. g. , close file) 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 15. 3: Using. Exceptions. java // Demonstration of the try-catch-finally exception handling mechanism. public class Using. Exceptions { Outline 15 public static void main( String args[] ) { try { throw. Exception(); // call method throw. Exception } // catch Exceptions thrown by method throw. Exception catch ( Exception exception ) { System. err. println( "Exception handled in main" ); } does. Not. Throw. Exception(); } Using. Exceptions. java // demonstrate try/catch/finally public static void throw. Exception() throws Exception { // throw an exception and immediately catch it try { System. out. println( "Method throw. Exception" ); throw new Exception(); // generate exception } 2003 Prentice Hall, Inc. All rights reserved.

27 28 29 30 31 32 33 34 35 36 37 38 39 40

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // catch exception thrown in try block catch ( Exception exception ) { System. err. println( "Exception handled in method throw. Exception" ); throw exception; // rethrow for further processing Outline 16 Rethrow Exception // any code here would not be reached } // this block executes regardless of what occurs in try/catch The finally block executes, finally { System. err. println( "Finally executed in throw. Exception" ); even though Exception thrown } Using. Exceptions. // any code here would not be reached } // end method throw. Exception // demonstrate finally when no exception occurs public static void does. Not. Throw. Exception() { // try block does not throw an exception try { System. out. println( "Method does. Not. Throw. Exception" ); } java Line 32 Lines 38 -40 2003 Prentice Hall, Inc. All rights reserved.

53 54 55 56 57 58 59 60 61 62 63 64 65 66

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 // catch does not execute, because no exception thrown catch ( Exception exception ) { System. err. println( exception ); } // this clause executes regardless of what occurs in try/catch finally { System. err. println( "Finally executed in does. Not. Throw. Exception" ); } Outline 17 The finally block always executes System. out. println( "End of method does. Not. Throw. Exception" ); } // end method does. Not. Throw. Exception } // end class Using. Exceptions Method throw. Exception handled in method throw. Exception Finally executed in throw. Exception handled in main Method does. Not. Throw. Exception Finally executed in does. Not. Throw. Exception End of method does. Not. Throw. Exception Using. Exceptions. java Lines 60 -63 2003 Prentice Hall, Inc. All rights reserved.

18 15. 7 Stack Unwinding • Exception not caught in scope – Method terminates

18 15. 7 Stack Unwinding • Exception not caught in scope – Method terminates – Stack unwinding occurs (all local variables go out of scope, control reverts to statement that called method) – Another attempt to catch exception (if this is inside a try block) – And on and on…. 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Outline // Fig. 15. 4: Using. Exceptions. java // Demonstration of stack unwinding. public class Using. Exceptions { public static void main( String args[] ) { // call throw. Exception to demonstrate stack unwinding try { throw. Exception(); } // catch exception thrown in throw. Exception catch ( Exception exception ) { System. err. println( "Exception handled in main" ); } } 19 Call method throw. Exception Using. Exceptions. Catch Exception from java method throw. Excetion Line 9 Line 13 // throw. Exception throws exception that is not caught in this method public static void throw. Exception() throws Exception { Line 19 Method declares a // throw an exception and catch it in main throws clause try { Line 24 System. out. println( "Method throw. Exception" ); throw new Exception(); // generate exception Throw an Exception } 2003 Prentice Hall, Inc. All rights reserved.

27 28 29 30 31 32 33 34 35 36 37 38 39 40

27 28 29 30 31 32 33 34 35 36 37 38 39 40 // catch is incorrect type, so Exception is not caught catch ( Runtime. Exception runtime. Exception ) { System. err. println( "Exception handled in method throw. Exception" ); } Outline 20 // finally clause always executes finally { System. err. println( "Finally is always executed" ); } } // end method throw. Exception } // end class Using. Exceptions Method throw. Exception Finally is always executed Exception handled in main Using. Exceptions. java 2003 Prentice Hall, Inc. All rights reserved.

15. 8 print. Stack. Trace, get. Stack. Trace and get. Message • Throwable class

15. 8 print. Stack. Trace, get. Stack. Trace and get. Message • Throwable class – Method print. Stack. Trace • Prints method call stack (helpful in debugging) – Method get. Stack. Trace • Obtains stack-trace information – Method get. Message • Returns descriptive string • Uncaught exception – default exception handler – displays complete stack trace 2003 Prentice Hall, Inc. All rights reserved. 21

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Outline // Fig. 15. 5: Using. Exceptions. java // Demonstrating get. Message and print. Stack. Trace from class Exception. public class Using. Exceptions { public static void main( String args[] ) { try { method 1(); // call method 1 } 22 Call method 1 // catch Exceptions thrown from method 1 catch ( Exception exception ) { System. err. println( exception. get. Message() + "n" ); exception. print. Stack. Trace(); Print information generated Using. Exceptions. by get. Message and java print. Stack. Trace // obtain the stack-trace information Stack. Trace. Element[] trace. Elements = exception. get. Stack. Trace(); Line 8 Lines 13 -14 Print Stack. Trace. Elements Lines 25 -26 System. out. println( "n. Stack trace from get. Stack. Trace: " ); System. out. println( "Classtt. Filettt. Linet. Method" ); // loop through trace. Elements to get exception description for ( int i = 0; i < trace. Elements. length; i++ ) { Stack. Trace. Element current. Element = trace. Elements[ i ]; System. out. print( current. Element. get. Class. Name() + "t" ); System. out. print( current. Element. get. File. Name() + "t" ); 2003 Prentice Hall, Inc. All rights reserved.

27 28 29 30 31 32 33 34 35 36 37 38 39 40

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 System. out. print( current. Element. get. Line. Number() + "t" ); System. out. print( current. Element. get. Method. Name() + "n" ); Outline 23 } // end for statement } // end catch } // end method main // call method 2; throw exceptions back to main public static void method 1() throws Exception { method 2(); } // call method 3; throw exceptions back to method 1 public static void method 2() throws Exception { method 3(); } // throw Exception back to method 2 public static void method 3() throws Exception { throw new Exception( "Exception thrown in method 3" ); } Print Stack. Trace. Elements Using. Exceptions. java method 1 declares a 27 -28 throw. Lines clause Call method 2 Line 37 Line 39 a method 2 declares throw clause Line 43 Call method 3 Line 45 method 3 declares a 49 throw. Line clause Throw an 51 Line Exception that propagates back to main 2003 Prentice Hall, Inc. All rights reserved.

53 54 } // end class Using Exceptions Outline 24 Exception thrown in method

53 54 } // end class Using Exceptions Outline 24 Exception thrown in method 3 java. lang. Exception: Exception thrown in method 3 at Using. Exceptions. method 3(Using. Exceptions. java: 51 ) at Using. Exceptions. method 2(Using. Exceptions. java: 45 ) at Using. Exceptions. method 1(Using. Exceptions. java: 39 ) at Using. Exceptions. main(Using. Exceptions. java: 8) Stack trace from get. Stack. Trace: Using. Exceptions. java 2003 Prentice Hall, Inc. All rights reserved.

25 15. 10 Declaring New Exception Types • Extend existing exception class public class

25 15. 10 Declaring New Exception Types • Extend existing exception class public class Too. Small. Exception extends Arithmetic. Exception { public Too. Small. Exception () { super (“Value is less than 100”); } public Too. Small. Exception (String message) { super (message); } } 2003 Prentice Hall, Inc. All rights reserved.

26 15. 11 Constructors and Exception Handling • Constructor cannot return a value to

26 15. 11 Constructors and Exception Handling • Constructor cannot return a value to indicate an error • Throw exception if constructor causes error – For example, if invalid initialization value given to constructor and there is no sensible way to correct this 2003 Prentice Hall, Inc. All rights reserved.