1 / 77

Chapter 12: Handling Exceptions and Events

Chapter 12: Handling Exceptions and Events. J ava P rogramming: From Problem Analysis to Program Design, Second Edition. Objectives. Learn what an exception is. See how a try / catch block is used to handle exceptions. Become aware of the hierarchy of exception classes.

lana
Download Presentation

Chapter 12: Handling Exceptions and Events

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 12: Handling Exceptions and Events JavaProgramming: From Problem Analysis to Program Design, Second Edition

  2. Objectives • Learn what an exception is. • See how a try/catch block is used to handle exceptions. • Become aware of the hierarchy of exception classes. • Learn about checked and unchecked exceptions. • Learn how to handle exceptions within a program. • Discover how to throw and rethrow an exception. • Learn how to handle events in a program. Java Programming: From Problem Analysis to Program Design, Second Edition

  3. Exception • An occurrence of an undesirable situation that can be detected during program execution. • Examples: • Division by zero. • Trying to open an input file that does not exist. • An array index that goes out of bounds. Java Programming: From Problem Analysis to Program Design, Second Edition

  4. import java.util.*;public class ExceptionExample1 {static Scanner console = new Scanner(System.in); public static void main (String[] args) {int dividend, divisor, quotient; System.out.print("Line 2: Enter the “ + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 5: Enter the “ + "divisor: "); divisor = console.nextInt();; System.out.println(); quotient = dividend / divisor; System.out.println("Line 9: Quotient = “ + quotient); }} Java Programming: From Problem Analysis to Program Design, Second Edition

  5. Sample Run2 Line 2: Enter the dividend: 24 Line 5: Enter the divisor: 0 Exception in thread "main“ java.lang.ArithmeticException: / by zero at ExceptionExample1.main(ExceptionExample1.java:23) Java Programming: From Problem Analysis to Program Design, Second Edition

  6. Sample Run3 Line 2: Enter the dividend: 2e Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:819) at java.util.Scanner.next(Scanner.java:1431) at java.util.Scanner.nextInt(Scanner.java:2040) at java.util.Scanner.nextInt(Scanner.java:2000) at ExceptionExample1.main(ExceptionExample1.java:15) Java Programming: From Problem Analysis to Program Design, Second Edition

  7. Handling Exceptions within a Program • Can use an if statement to handle an exception. Java Programming: From Problem Analysis to Program Design, Second Edition

  8. import java.util.*;public class ExceptionExample2{static Scanner console = new Scanner(System.in);public static void main (String[] args) {int dividend, divisor, quotient; System.out.print("Line 2: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 5: Enter the " + "divisor: "); divisor = console.nextInt();; System.out.println(); if (divisor != 0) { quotient = dividend / divisor; System.out.println("Line 10: " + "Quotient = " + quotient); }else System.out.println("Line 11: Cannot " + "divide by zero."); }} Java Programming: From Problem Analysis to Program Design, Second Edition

  9. Handling Exceptions within a Program • However, suppose that division by zero occurs in more than one place within the same block. • In this case, using ifstatements may not be the most effective way to handle the exception. Java Programming: From Problem Analysis to Program Design, Second Edition

  10. Java’s Mechanism of Exception Handling • With exception handling, a program can continue executing after dealing with a problem. • When an exception occurs, an object of a particular exception classis created. • Java provides a number of exception classes to effectively handle certain common exceptions, such as: • Division by zero • Invalid input • File not found Java Programming: From Problem Analysis to Program Design, Second Edition

  11. Java’s Mechanism of Exception Handling • Division by zero is: • An arithmetic error. • Handled by the classArithmeticException. • When a division by zero exception occurs, the program creates an object of the classArithmeticException. Java Programming: From Problem Analysis to Program Design, Second Edition

  12. Java’s Mechanism of Exception Handling • When a Scanner object is used to input data into a program, any invalid input errors are handled using the classInputMismatchException. • The classException (directly or indirectly) is the superclass of all the exception classes in Java. Java Programming: From Problem Analysis to Program Design, Second Edition

  13. try/catch/finally Block • Statements that might generate an exception are placed in a tryblock. • The tryblock: • Might also contain statements that should not be executed if an exception occurs. • Is followed by zero or more catchblocks. • A catchblock: • Specifies the type of exception it can catch. • Contains an exception handler. Java Programming: From Problem Analysis to Program Design, Second Edition

  14. try/catch/finallyBlock • The last catchblock may or may not be followed by a finallyblock. • Any code contained in a finallyblock always executes regardless of whether an exception occurs, except when the program exits early from a tryblock by calling the method System.exit. • If a tryblock has no catchblock, then it must have the finallyblock. Java Programming: From Problem Analysis to Program Design, Second Edition

  15. try/catch/finallyBlock Java Programming: From Problem Analysis to Program Design, Second Edition

  16. try/catch/finallyBlock • If no exception is thrown in a tryblock, all catchblocks associated with the tryblock are ignored and program execution resumes after the last catchblock. • If an exception is thrown in a tryblock, the remaining statements in the tryblock are ignored. • The program searches the catchblocks in the order in which they appear after the tryblock and looks for an appropriate exception handler. Java Programming: From Problem Analysis to Program Design, Second Edition

  17. try/catch/finallyBlock • If the type of the thrown exception matches the parameter type in one of the catchblocks, the code of that catchblock executes and the remaining catchblocks are ignored. • If there is a finallyblock after the last catchblock, the finallyblock executes regardless of whether an exception occurs. Java Programming: From Problem Analysis to Program Design, Second Edition

  18. Order of catch Blocks • The heading of a catchblock specifies the type of exception it handles. • A catchblock can catch either all exceptions of a specific type or all types of exceptions. • A reference variable of a superclass type can point to an object of its subclass. Java Programming: From Problem Analysis to Program Design, Second Edition

  19. Order of catch Blocks • If you declare an exception using the classException in the heading of a catchblock, then that catchblock can catch all types of exceptions because the classException is the superclass of all exception classes. Java Programming: From Problem Analysis to Program Design, Second Edition

  20. Order of catch Blocks • In a sequence of catchblocks following a tryblock, a catchblock that declares an exception of a subclass type should be placed before catchblocks that declare exceptions of a superclass type. • It is a syntax error if a catch that catches a superclass object is placed before a catch that catches an object of a subclass of that superclass Java Programming: From Problem Analysis to Program Design, Second Edition

  21. import java.util.*;public class ExceptionExample3{static Scanner console = new Scanner(System.in);public static void main (String[] args) {int dividend, divisor, quotient; try { System.out.print("Line 4: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 7: Enter the " + "divisor: "); divisor = console.nextInt(); System.out.println(); quotient = dividend / divisor; //line 10 System.out.println("Line 11: Quotient = " + quotient); }catch (ArithmeticException aeRef) //line 12 { System.out.println("Line 13: Exception " + aeRef.toString()); }catch (InputMismatchException imeRef) { System.out.println("Line 15: Exception " + imeRef.toString()); } }} Java Programming: From Problem Analysis to Program Design, Second Edition

  22. Sample Run2 Line 4: Enter the dividend: 18 Line 7: Enter the divisor: 0 Line 13: Exception java.lang.ArithmeticException: / by zero The statement in line 10 throws an ArithmeticException,which is caught by the catch block starting at Line 12. Java Programming: From Problem Analysis to Program Design, Second Edition

  23. Sample Run3 Line 4: Enter the dividend: 2753 Line 7: Enter the divisor: 2f1 Line 15: Exception java.util.InputMismatchException The statement in line 8 throws an InputMismatchException. Tis exception is thrown by the method nextInt of the class Scanner. The catch block starting at Line 14 catches this exception . Java Programming: From Problem Analysis to Program Design, Second Edition

  24. 2f1stays as the next input token in the input stream If the input token is invalid, the method nextInt does not remove that input token from the input stream. catch (InputMismatchException imeRef) {String str; str = console.next(); System.out.println("Line 17: Exception " + imeRef.toString() + " " + str ); } Java Programming: From Problem Analysis to Program Design, Second Edition

  25. Sample Run3 Line 4: Enter the dividend: 2753 Line 7: Enter the divisor: 2f1 Line 17: Exception java.util.InputMismatchException 2f1 Java Programming: From Problem Analysis to Program Design, Second Edition

  26. The exception classes provided by Java Java Programming: From Problem Analysis to Program Design, Second Edition

  27. Order of catch Blocks Java Programming: From Problem Analysis to Program Design, Second Edition

  28. Order of catch Blocks Java Programming: From Problem Analysis to Program Design, Second Edition

  29. Order of catch Blocks Java Programming: From Problem Analysis to Program Design, Second Edition

  30. Order of catch Blocks Java Programming: From Problem Analysis to Program Design, Second Edition

  31. Java’s Exception Class • classException: • Subclass of classThrowable. • Superclass of classes designed to handle exceptions. • Various types of exceptions: • I/O exceptions. • Number format exceptions. • File not found exceptions. • Array index out of bounds exceptions. • Various exceptions categorized into separate classes and contained in various packages. Java Programming: From Problem Analysis to Program Design, Second Edition

  32. Java’s Exception Class Java Programming: From Problem Analysis to Program Design, Second Edition

  33. Java’s Exception Class Java Programming: From Problem Analysis to Program Design, Second Edition

  34. Java’s Exception Class Java Programming: From Problem Analysis to Program Design, Second Edition

  35. Java’s Exception Class Java Programming: From Problem Analysis to Program Design, Second Edition

  36. Java’s Exception Class Java Programming: From Problem Analysis to Program Design, Second Edition

  37. Java’s Exception Class Java Programming: From Problem Analysis to Program Design, Second Edition

  38. After a method throws an exception, the runtime system attempts to find something to handle it. Java Programming: From Problem Analysis to Program Design, Second Edition

  39. The list of methods is known as the call stack Java Programming: From Problem Analysis to Program Design, Second Edition

  40. Searching the call stack for the exception handler. Java Programming: From Problem Analysis to Program Design, Second Edition

  41. Checked Exceptions • Any exception that can be recognized by the compiler. • Example: • FileNotFoundExceptions. Java Programming: From Problem Analysis to Program Design, Second Edition

  42. Unchecked Exceptions • Exceptions that cannot be recognized when the program compiles (must be checked for by programmer). • Examples: • Division by zero • Array index out of bounds • Syntax: throws ExceptionType1, ExceptionType2,... ExceptionType1, ExceptionType2, and so on are names of exception classes Java Programming: From Problem Analysis to Program Design, Second Edition

  43. Checked and Unchecked Exceptions • If a checked exception is thrown by a method , or if that method calls methods that throw a checked exceptions, each of those exceptions must be declared in the throws clause of that method or caught in a try/catch in that method. Java Programming: From Problem Analysis to Program Design, Second Edition

  44. Exceptions Example Code public static void exceptionMethod() throws InputMismatchException, FileNotFoundException { //statements } • The method exceptionMethod throws exceptions of the type InputMismatchException and FileNotFoundException. Java Programming: From Problem Analysis to Program Design, Second Edition

  45. The classException and the Operator instanceof • A reference of a superclass type can point to objects of its subclass. • You can determine if a reference variable points to an object using the operator instanceof. • You can combine catch blocks using this facility. Java Programming: From Problem Analysis to Program Design, Second Edition

  46. try { System.out.print("Line 4: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 7: Enter the " + "divisor: "); divisor = console.nextInt(); System.out.println(); quotient = dividend / divisor; System.out.println("Line 11: Quotient = " + quotient); } catch (Exception eRef) { if (eRef instanceof ArithmeticException) System.out.println("Line 14: Exception " + eRef.toString() + ”division by zero”); else if (eRef instanceof InputMismatchException) System.out.println("Line 16: Exception " + eRef.toString() + “invalid input”); } Java Programming: From Problem Analysis to Program Design, Second Edition

  47. Example 12-6 Java Programming: From Problem Analysis to Program Design, Second Edition

  48. int dividend, divisor; double quotient; try { System.out.print("Line 4: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 7: Enter the " + "divisor: "); divisor = console.nextInt(); System.out.println(); quotient = (double) dividend / divisor; System.out.println("Line 11: Quotient = " + quotient); } catch (ArithmeticException aeRef) { System.out.println("Line 13: Exception " + aeRef.toString()); } catch (InputMismatchException imeRef) { System.out.println("Line 15: Exception " + imeRef.toString()); }} Java Programming: From Problem Analysis to Program Design, Second Edition

  49. Sample run Line 4: Enter the dividend: 12 Line 7: Enter the divisor: 0 Line 11: Quotient = Infinity Java Programming: From Problem Analysis to Program Design, Second Edition

  50. public static void main (String[] args) { int dividend, divisor;double quotient; try { System.out.print("Line 4: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 7: Enter the " + "divisor: "); divisor = console.nextInt(); System.out.println(); quotient = result(dividend,divisor); System.out.println("Line 11: Quotient = " + quotient); }catch (ArithmeticException aeRef){ System.out.println("Line 13: Exception " + aeRef.toString()); } catch (InputMismatchException imeRef) { System.out.println("Line 15: Exception " + imeRef.toString()); }} public static double result( int number1, int number2)throws ArithmeticException { if (number2 == 0) thrownew ArithmeticException("Attempted to divid by zero"); return (double) number1 / number2; } Java Programming: From Problem Analysis to Program Design, Second Edition

More Related