Lecture 11: Exception Handling PDF

Summary

This document provides a lecture on exception handling in programming, particularly in Java. It covers different types of exceptions, how to handle them, and various examples.

Full Transcript

1 Lecture 11: Exception Handling 2 Outlines 1. Introduction 2. Exception-Handling Overview 3. Exception-Handling Example: Divide by Zero 4. Java Exception Hierarchy 5. finally Clause 6. Stack Unwinding 7. printStackTrace, getStackTrace and getMessa...

1 Lecture 11: Exception Handling 2 Outlines 1. Introduction 2. Exception-Handling Overview 3. Exception-Handling Example: Divide by Zero 4. Java Exception Hierarchy 5. finally Clause 6. Stack Unwinding 7. printStackTrace, getStackTrace and getMessage 3 Introduction An Exception is an indication of a problem that occurs during a program’s execution – E.g., divide by zero Exception handling enables programmers to create applications that can resolve (or handle) exceptions Exception handling enables programmers to write stable programs 4 Exception-Handling Overview Exception handling is designed to process synchronous errors ‫يقوتم يغلا اطخألا‬, which occur when a statement executes. Examples: – Out-of-range Array – Arithmetic overflow (a value outside the representable range of values) – Calculation errors (i.e. divide by 0) – Conversion errors (i.e. convert ‘q’ to a number) – Memory errors (i.e. memory incorrectly allocated, memory leaks, “null pointer”) – File system errors (i.e. disk is full, disk has been removed) – Network errors (i.e. network is down, URL does not exist) 5 Exception-Handling Overview Exception handler is the code that executes when the program detects an exception and it process the kind of exception ‫جت اي يغط ماج طل ح يا ه يف تمغا جخا وتل ا اطخأ‬ ‫خخا عمغ لمغ ا تاع خب يغقتل‬ When the methods detect the problem, it will throws an exception 6 Exception-Handling Overview The exception handler catches and handles the exception try statements: try { // Code that could generate errors ‫فطم ي يغط ماج يغطف يي أط طج في ح يا تم وتل ا اطخأ‬ } catch( Exception_Type exception) { // Code for error handling ‫يغ ت يغ ققو غ لمغ ا يغقتل يغلا اطخأ‬ } 7 Exception-Handling Overview try { } catch( Exception_Type exception) { 1. An optional clause 2. Always executes whether or not an exception occurs } 3. Prevent “resource leaks” finally { //resource release statements } ‫‪8‬‬ ‫ يط ة ابخ وتل ا اطخأ يف يغلطم ض أل‪2‬‬ ‫{ ‪try‬‬ ‫;‪Statement1‬‬ ‫رابعل ت يفنقتا ت رن عل ذيفنق قوت ‪، 2‬‬ ‫عرقو‬ ‫‪.1‬‬ ‫;‪Statement2‬‬ ‫لقع ت فاننبل يوق ‪ throws‬ذخلل ‪Exception‬‬ ‫;‪Statement3‬‬ ‫}‬ ‫)‪catch( Exception_Type exception‬‬ ‫{‬ ‫‪.2‬ارلق رابعل ت فاننبل ب ا ذيف تفنق ‪catch‬‬ ‫رت بلنقنل نقة ت خلل ت وقلق اقة ت خلل تي تفنقتا ت اا ‪catch‬‬ ‫}‬ ‫;‪Statement4‬‬ ‫‪.3‬تي لن ل ت ولن لل رت رابعل تفنقتا ت اا ‪ catch‬ت وياع‬ ‫‪.4‬ارلق رابعل ت فاننبل ب ا ذيف تفنق يا ليفعل ت اا ‪catch‬‬ ‫عرت ربن ق لعل تفنقتا ت اا ‪try‬‬ 9 Example Output: Division by zero. After catch statement. ‫‪10‬‬ ‫‪Exception-Handling Example: Divide by‬‬ ‫‪Zero‬‬ ‫ يةطع ع ماج خخا عل ة يغيمجم يغطمغااا‬ ‫ خخا يغ اطق ا عماومب يغ أل يق ب يغ م ف‪.‬عل ياومب يغ أل يغ م ف‬ ‫خخا يغط ماج ع ابم تممس أا ا يغ أل يق ب فرب يغ م ف‬ ‫ خخا يغط ماج ع لمغ ا يقوتم يغلا اطخألا ةمغخا ا فرب مي‬ ‫ا (‬ ‫أ أوتم يااومب )ياومب ت‬ 11 Exception-Handling Example: Divide by Zero 12 1 // DivideByZeroTest.java 2 // An exception-handling example that checks for divide-by-zero. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class DivideByZeroTest extends JFrame implements ActionListener { 9 private JTextField inputField1, inputField2, outputField; 10 private int number1, number2, result; 11 12 // set up GUI 13 public DivideByZeroTest() 14 { 15 super( "Demonstrating Exceptions" ); 16 17 // get content pane and set its layout 18 Container container = getContentPane(); 19 container.setLayout( new GridLayout( 3, 2 ) ); 13 20 // set up label and inputField1 21 container.add(new JLabel( "Enter numerator)); 22 inputField1 = new JTextField(); 23 container.add( inputField1 ); 25 // set up label and inputField2; register listener 26 container.add( new JLabel( "Enter denominator and press Enter") ); 27 inputField2 = new JTextField(); 28 container.add( inputField2 ); 29 inputField2.addActionListener( this ); 30 31 // set up label and outputField 32 container.add( new JLabel( "RESULT ") ); 33 outputField = new JTextField(); 34 container.add( outputField ); 35 36 setSize( 425, 100 ); 37 setVisible( true ); 38 39 } // end DivideByZeroTest constructor 14 40 // process GUI events 41 public void actionPerformed( ActionEvent event ) 42 { 43 outputField.setText( "" ); // clear outputField 44 45 // read two numbers and calculate quotient 46 try { 47 number1 = Integer.parseInt( inputField1.getText() ); 48 number2 = Integer.parseInt( inputField2.getText() ); 49 result = quotient( number1, number2 ); 50 outputField.setText( String.valueOf( result ) ); 51 } 52 53 // process improperly formatted input 54 catch ( NumberFormatException numberFormatException ) { 55 JOptionPane.showMessageDialog( this, 56 "You must enter two integers", "Invalid Number Format", 57 JOptionPane.ERROR_MESSAGE ); 58 } 15 59 // process attempts to divide by zero 60 catch ( ArithmeticException arithmeticException ) { 61 JOptionPane.showMessageDialog( this, 62 arithmeticException.toString(), "Arithmetic Exception", 63 JOptionPane.ERROR_MESSAGE ); 64 } 65 } // end method actionPerformed // demonstrates throwing an exception when a divide-by-zero occurs 67 public int quotient( int numerator, int denominator ) 68 throws ArithmeticException 69 { 70 return numerator / denominator; 71 } 73 public static void main( String args[] ) 74 { 75 DivideByZeroTest application = new DivideByZeroTest(); 76 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 77 } 78 } // end class DivideByZeroTest 16 Java Exception Hierarchy Superclass Throwable 1. Subclass Exception Exceptional situation that could occur in a java program and be caught by the application 2. Subclass Error Typically not caught by program Checked exceptions – Catch or declare Unchecked exceptions 17 Java Exception Hierarchy 18 Checked Exceptions Inherit from class Exception Compiler enforces catch-or-declare requirement Compiler checks each method call and method declaration – determines whether method throws checked exceptions. – If so, the compiler ensures checked exception caught or declared in throws clause. – If not caught or declared, compiler error occurs. 19 Unchecked Exceptions Inherit from class RuntimeException Compiler does not check code to see if exception caught or declared If an unchecked exception occurs and not caught – Program terminates or runs with unexpected results Can typically be prevented by proper coding 20 finally Clause Resource leak – Caused when resources are not released by a program – For example: Files, database connections and networks connections that are not closed properly might not be available for use in other programs The finally block – Appears after catch blocks – Always executes – Use to release resources 21 Example(2) :‫بن ي بخالنا ت فاننبل ت رن ي‬ public class UsingExceptions { public static void main( String args[] ) { try { test1(); } catch ( Exception exception ) { System.out.println( "Exception handled in main" ); } test2(); } // end main 22 public static void test1() throws Exception { try { System.out.println( "Method test1" ); throw new Exception(); // generate exception } catch ( Exception exception ) { System.out.println( "Exception handled in test1" ); } finally { System.out.println( "Finally executed in test1" ); } } // end method test1 23 public static void test2() { try { System.out.println( "Method test2" ); } catch ( Exception exception ) { System.out.println( exception.toString()); } finally { System.out.println("Finally executed in test2" ); } System.out.println( "End of method test2" ); } // end method test2 } // end class UsingExceptions 24 Output Method test1 Exception handled in test1 Finally executed in test1 Method test2 Finally executed in test2 End of method test2 25 Example(3) : ‫ بن ي ت وخالنا‬،test1 ‫ ووان ريا ق ت فاننبل ت بن تي ت ات ل‬ public static void test1() throws Exception { try { System.out.println( "Method test1" ); throw new Exception(); // generate exception } catch ( Exception exception ) { System.out.println( "Exception handled in test1" ); throw new exception(); } finally { System.out.println( "Finally executed in test1" ); } } // end method test1 26 Output Method test1 Exception handled in test1 Finally executed in test1 Exception handled in main Method test2 Finally executed in test2 End of method test2 27 Stack Unwinding Exception not caught in scope – Method terminates – Stack unwinding occurs – Another attempt to catch exception 28 Example(4) :‫بن ي بخالنا ت فاننبل ت رن ي‬ public class UsingExceptions2 { public static void main( String args[] ) { try { test1(); } catch ( Exception exception ) { System.out.println( "Exception handled in main" ); } } 29 public static void test1() throws Exception { try { System.out.println( "Method test1" ); throw new Exception(); // generate exception } catch ( RuntimeException runtimeException ) { System.out.println( "Exception handled in test1" ); } finally { System.out.println( "Finally is always executed" ); } } // end method test1 } // end class UsingExceptions2 30 Output Method test1 Finally is always executed Exception handled in main printStackTrace, getStackTrace and 31 getMessage Throwable class – Method printStackTrace Prints method call stack java.lang.NullPointerException at MyClass.mash(MyClass.java‫ا‬9) at MyClass.crunch(MyClass.java‫ا‬6) at MyClass.main(MyClass.java‫ا‬3) – Method getStackTrace Obtains stack-trace information – Method getMessage Returns descriptive string 32 public class UsingExceptions { Example(5) public static void main( String args[] ) { try { method1(); } catch ( Exception exception ) { System.out.println( exception.getMessage() + "\n" ); exception.printStackTrace(); StackTraceElement[] traceElements = exception.getStackTrace(); System.out.println( "\nStack trace from getStackTrace:" ); System.out.println( "Class\t\tFile\t\t\tLine\tMethod" ); 33 // 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" ); System.out.print( currentElement.getLineNumber() + "\t" ); System.out.print( currentElement.getMethodName() + "\n" ); } // end for statement } // end catch } // end method main 34 // call method2; throw exceptions back to main public static void method1() throws Exception { method2(); } // call method3; throw exceptions back to method1 public static void method2() throws Exception { method3(); } // throw Exception back to method2 public static void method3() throws Exception { throw new Exception( "Exception thrown in method3" ); } 35 Output Exception thrown in method3 getMessage() 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) printStackTrace() Stack trace from getStackTrace: Class File Line Method UsingExceptions UsingExceptions.java 51 method3 UsingExceptions UsingExceptions.java 45 method2 UsingExceptions UsingExceptions.java 39 method1 UsingExceptions UsingExceptions.java 8 main

Use Quizgecko on...
Browser
Browser