Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 15 – Exception Handling

Similar presentations


Presentation on theme: "Chapter 15 – Exception Handling"— Presentation transcript:

1 Chapter 15 – Exception Handling
Outline Introduction Exception-Handling Overview Exception-Handling Example: Divide by Zero Java Exception Hierarchy Rethrowing an Exception finally Clause Stack Unwinding printStackTrace, getStackTrace and getMessage Chained Exceptions Declaring New Exception Types Constructors and Exception Handling

2 15.1 Introduction Exception handling Exception Chained exceptions
Indication of problem during execution E.g., divide by zero Chained exceptions

3 15.2 Exception-Handling Overview
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

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 throws clause specifies exceptions method throws

5 15.3 Exception-Handling Example: Divide by Zero
Common programming mistake Throws ArithmeticException

6 DivideByZeroTest.java 1 // Fig. 15.1: DivideByZeroTest.java
// An exception-handling example that checks for divide-by-zero. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class DivideByZeroTest extends JFrame implements ActionListener { 9 private JTextField inputField1, inputField2, outputField; private int number1, number2, result; 12 // set up GUI public DivideByZeroTest() { super( "Demonstrating Exceptions" ); 17 // get content pane and set its layout Container container = getContentPane(); container.setLayout( new GridLayout( 3, 2 ) ); 21 // set up label and inputField1 container.add( new JLabel( "Enter numerator ", SwingConstants.RIGHT ) ); inputField1 = new JTextField(); container.add( inputField1 ); DivideByZeroTest.java

7 DivideByZeroTest.java Line 51 Lines 52-53
27 // set up label and inputField2; register listener container.add( new JLabel( "Enter denominator and press Enter ", SwingConstants.RIGHT ) ); inputField2 = new JTextField(); container.add( inputField2 ); inputField2.addActionListener( this ); 34 // set up label and outputField container.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) ); outputField = new JTextField(); container.add( outputField ); 39 setSize( 425, 100 ); setVisible( true ); 42 } // end DivideByZeroTest constructor 44 // process GUI events public void actionPerformed( ActionEvent event ) { outputField.setText( "" ); // clear outputField 49 // read two numbers and calculate quotient try { number1 = Integer.parseInt( inputField1.getText() ); number2 = Integer.parseInt( inputField2.getText() ); DivideByZeroTest.java Line 51 Lines 52-53 The try block Read integers from JTextFields

8 DivideByZeroTest.java Line 55 Line 60 Line 67 Line 77
54 result = quotient( number1, number2 ); outputField.setText( String.valueOf( result ) ); } 58 // process improperly formatted input catch ( NumberFormatException numberFormatException ) { JOptionPane.showMessageDialog( this, "You must enter two integers", "Invalid Number Format", JOptionPane.ERROR_MESSAGE ); } 65 // process attempts to divide by zero catch ( ArithmeticException arithmeticException ) { JOptionPane.showMessageDialog( this, arithmeticException.toString(), "Arithmetic Exception", JOptionPane.ERROR_MESSAGE ); } 72 } // end method actionPerformed 74 // demonstrates throwing an exception when a divide-by-zero occurs public int quotient( int numerator, int denominator ) throws ArithmeticException { return numerator / denominator; } Method quotient attempts division DivideByZeroTest.java Line 55 Line 60 Line 67 Line 77 Catch NumberFormatException Catch ArithmeticException Method quotient throws ArithmeticException

9 DivideByZeroTest.java 81 82 public static void main( String args[] )
{ DivideByZeroTest application = new DivideByZeroTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 87 88 } // end class DivideByZeroTest DivideByZeroTest.java

10 15.4 Java Exception Hierarchy
Superclass Throwable Subclass Exception Exceptional situations Should be caught by program Subclass Error Typically not caught by program Checked exceptions Catch or declare Unchecked exceptions

11 Fig. 15.2 Inheritance hierarchy for class Throwable
Exception Error AWTError ThreadDeath IOException RuntimeException OutOfMemoryError

12 15.5 Rethrowing an Exception
Rethrow exception if catch cannot handle it

13 15.6 finally Clause Resource leak The finally block
Caused when resources are not released by a program The finally block Appears after catch blocks Always executes Use to release resources

14 UsingExceptions.java 1 // Fig. 15.3: UsingExceptions.java
// Demonstration of the try-catch-finally exception handling mechanism. public class UsingExceptions { 4 public static void main( String args[] ) { try { throwException(); // call method throwException } 10 // catch Exceptions thrown by method throwException catch ( Exception exception ) { System.err.println( "Exception handled in main" ); } 15 doesNotThrowException(); } 18 // demonstrate try/catch/finally public static void throwException() throws Exception { // throw an exception and immediately catch it try { System.out.println( "Method throwException" ); throw new Exception(); // generate exception } UsingExceptions.java

15 UsingExceptions.java Line 32 Lines 38-40
27 // catch exception thrown in try block catch ( Exception exception ) { System.err.println( "Exception handled in method throwException" ); throw exception; // rethrow for further processing 33 // any code here would not be reached } 36 // this block executes regardless of what occurs in try/catch finally { System.err.println( "Finally executed in throwException" ); } 41 // any code here would not be reached 43 } // end method throwException 45 // demonstrate finally when no exception occurs public static void doesNotThrowException() { // try block does not throw an exception try { System.out.println( "Method doesNotThrowException" ); } UsingExceptions.java Line 32 Lines 38-40 Rethrow Exception The finally block executes, even though Exception thrown

16 UsingExceptions.java Lines 60-63
53 // catch does not execute, because no exception thrown catch ( Exception exception ) { System.err.println( exception ); } 58 // this clause executes regardless of what occurs in try/catch finally { System.err.println( "Finally executed in doesNotThrowException" ); } 64 System.out.println( "End of method doesNotThrowException" ); 66 } // end method doesNotThrowException 68 69 } // end class UsingExceptions UsingExceptions.java Lines 60-63 The finally block always executes Method throwException Exception handled in method throwException Finally executed in throwException Exception handled in main Method doesNotThrowException Finally executed in doesNotThrowException End of method doesNotThrowException

17 Exception not caught in scope
15.7 Stack Unwinding Exception not caught in scope Method terminates Stack unwinding occurs Another attempt to catch exception

18 UsingExceptions.java Line 9 Line 13 Line 19 Line 24
// Fig. 15.4: UsingExceptions.java // Demonstration of stack unwinding. public class UsingExceptions { 4 public static void main( String args[] ) { // call throwException to demonstrate stack unwinding try { throwException(); } 11 // catch exception thrown in throwException catch ( Exception exception ) { System.err.println( "Exception handled in main" ); } } 17 // throwException throws exception that is not caught in this method public static void throwException() throws Exception { // throw an exception and catch it in main try { System.out.println( "Method throwException" ); throw new Exception(); // generate exception } 26 UsingExceptions.java Line 9 Line 13 Line 19 Line 24 Call method throwException Catch Exception from method throwExcetion Method declares a throws clause Throw an Exception

19 27 // catch is incorrect type, so Exception is not caught
catch ( RuntimeException runtimeException ) { System.err.println( "Exception handled in method throwException" ); } 32 // finally clause always executes finally { System.err.println( "Finally is always executed" ); } 37 } // end method throwException 39 40 } // end class UsingExceptions UsingExceptions.java  Method throwException Finally is always executed Exception handled in main

20 15.8 printStackTrace, getStackTrace and getMessage
Throwable class Method printStackTrace Prints method call stack Method getStackTrace Obtains stack-trace information Method getMessage Returns descriptive string

21 UsingExceptions.java Line 8 Lines 13-14 Lines 25-26
// Fig. 15.5: UsingExceptions.java // Demonstrating getMessage and printStackTrace from class Exception. public class UsingExceptions { 4 public static void main( String args[] ) { try { method1(); // call method1 } 10 // catch Exceptions thrown from method1 catch ( Exception exception ) { System.err.println( exception.getMessage() + "\n" ); exception.printStackTrace(); 15 // obtain the stack-trace information StackTraceElement[] traceElements = exception.getStackTrace(); 18 System.out.println( "\nStack trace from getStackTrace:" ); System.out.println( "Class\t\tFile\t\t\tLine\tMethod" ); 21 // loop through traceElements to get exception description for ( int i = 0; i < traceElements.length; i++ ) { StackTraceElement currentElement = traceElements[ i ]; System.out.print( currentElement.getClassName() + "\t" ); System.out.print( currentElement.getFileName() + "\t" ); UsingExceptions.java Line 8 Lines Lines 25-26 Call method1 Print information generated by getMessage and printStackTrace Print StackTraceElements

22 Print StackTraceElements
System.out.print( currentElement.getLineNumber() + "\t" ); System.out.print( currentElement.getMethodName() + "\n" ); 29 } // end for statement 31 } // end catch 33 } // end method main 35 // call method2; throw exceptions back to main public static void method1() throws Exception { method2(); } 41 // call method3; throw exceptions back to method1 public static void method2() throws Exception { method3(); } 47 // throw Exception back to method2 public static void method3() throws Exception { throw new Exception( "Exception thrown in method3" ); } Print StackTraceElements UsingExceptions.java Lines Line 37 Line 39 Line 43 Line 45 Line 49 Line 51 method1 declares a throw clause Call method2 method2 declares a throw clause Call method3 method3 declares a throw clause Throw an Exception that propagates back to main

23 53 54 } // end class Using Exceptions
Exception thrown in method3 java.lang.Exception: Exception thrown in method3 at UsingExceptions.method3(UsingExceptions.java:51) at UsingExceptions.method2(UsingExceptions.java:45) at UsingExceptions.method1(UsingExceptions.java:39) at UsingExceptions.main(UsingExceptions.java:8) Stack trace from getStackTrace: Class File Line Method UsingExceptions UsingExceptions.java method3 UsingExceptions UsingExceptions.java method2 UsingExceptions UsingExceptions.java method1 UsingExceptions UsingExceptions.java main UsingExceptions.java

24 Wraps existing exception in a new exception
15.9 Chained Exceptions Wraps existing exception in a new exception enables exception to maintain complete stack-trace

25 UsingChainedExceptions.java Line 8 Lines 12-14 Line 18 Line 21 Line 26
// Fig. 15.6: UsingChainedExceptions.java // Demonstrating chained exceptions. public class UsingChainedExceptions { 4 public static void main( String args[] ) { try { method1(); // call method1 } 10 // catch Exceptions thrown from method1 catch ( Exception exception ) { exception.printStackTrace(); } } 16 // call method2; throw exceptions back to main public static void method1() throws Exception { try { method2(); // call method2 } 23 // catch Exception thrown from method2 catch ( Exception exception ) { throw new Exception( "Exception thrown in method1", exception ); UsingChainedExceptions.java Line 8 Lines Line 18 Line 21 Line 26 Call method1 Catch Exception and print stack trace method1 declares a throw clause Call method2 An existing Exception is chained to another

26 UsingChainedExceptions.java Line 31 Line 34 Line 39 Line 46
} } 29 // call method3; throw exceptions back to method1 public static void method2() throws Exception { try { method3(); // call method3 } 36 // catch Exception thrown from method3 catch ( Exception exception ) { throw new Exception( "Exception thrown in method2", exception ); } } 42 // throw Exception back to method2 public static void method3() throws Exception { throw new Exception( "Exception thrown in method3" ); } 48 49 } // end class Using Exceptions UsingChainedExceptions.java Line 31 Line 34 Line 39 Line 46 method2 declares a throw clause Call method3 An existing Exception is chained to another Throw a new Exception

27 java.lang.Exception: Exception thrown in method1
at UsingChainedExceptions.method1(UsingChainedExceptions.java:26) at UsingChainedExceptions.main(UsingChainedExceptions.java:8) Caused by: java.lang.Exception: Exception thrown in method2 at UsingChainedExceptions.method2(UsingChainedExceptions.java:39) at UsingChainedExceptions.method1(UsingChainedExceptions.java:21) ... 1 more Caused by: java.lang.Exception: Exception thrown in method3 at UsingChainedExceptions.method3(UsingChainedExceptions.java:46) at UsingChainedExceptions.method2(UsingChainedExceptions.java:34) ... 2 more UsingChainedExceptions.java

28 15.10 Declaring New Exception Types
Extend existing exception class

29 15.11 Constructors and Exception Handling
Throw exception if constructor causes error


Download ppt "Chapter 15 – Exception Handling"

Similar presentations


Ads by Google