Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Java Programming: From Problem Analysis to Program Design, 3e Chapter 12 Handling Exceptions and Events
  2. 2. Chapter Objectives <ul><li>Learn what an exception is </li></ul><ul><li>See how a try / catch block is used to handle exceptions </li></ul><ul><li>Become aware of the hierarchy of exception classes </li></ul><ul><li>Learn about checked and unchecked exceptions </li></ul>
  3. 3. Chapter Objectives (continued) <ul><li>Learn how to handle exceptions within a program </li></ul><ul><li>Discover how to throw and rethrow an exception </li></ul><ul><li>Learn how to handle events in a program </li></ul>
  4. 4. Exception <ul><li>Definition: an occurrence of an undesirable situation that can be detected during program execution </li></ul><ul><li>Examples </li></ul><ul><ul><li>Division by zero </li></ul></ul><ul><ul><li>Trying to open an input file that does not exist </li></ul></ul><ul><ul><li>An array index that goes out of bounds </li></ul></ul>
  5. 5. Handling Exception within a Program <ul><li>Can use an if statement to handle an exception </li></ul><ul><li>However, suppose that division by zero occurs in more than one place within the same block </li></ul><ul><ul><li>In this case, using if statements may not be the most effective way to handle the exception </li></ul></ul>
  6. 6. Java’s Mechanism of Exception Handling <ul><li>When an exception occurs, an object of a particular exception class is created </li></ul><ul><li>Java provides a number of exception classes to effectively handle certain common exceptions such as division by zero, invalid input, and file not found </li></ul><ul><li>Division by zero is an arithmetic error and is handled by the class ArithmeticException </li></ul>
  7. 7. Java’s Mechanism of Exception Handling (continued) <ul><li>When a division by zero exception occurs, the program creates an object of the class ArithmeticException </li></ul><ul><li>When a Scanner object is used to input data into a program, any invalid input errors are handled using the class InputMismatchException </li></ul><ul><li>The class Exception (directly or indirectly) is the superclass of all the exception classes in Java </li></ul>
  8. 8. try / catch / finally Block <ul><li>Statements that might generate an exception are placed in a try block </li></ul><ul><li>The try block might also contain statements that should not be executed if an exception occurs </li></ul><ul><li>The try block is followed by zero or more catch blocks </li></ul><ul><li>A catch block specifies the type of exception it can catch and contains an exception handler </li></ul>
  9. 9. try / catch / finally Block (continued) <ul><li>The last catch block may or may not be followed by a finally block </li></ul><ul><li>Any code contained in a finally block always executes, regardless of whether an exception occurs, except when the program exits early from a try block by calling the method System.exit </li></ul><ul><li>If a try block has no catch block, then it must have the finally block </li></ul>
  10. 10. try / catch / finally Block (continued)
  11. 11. try / catch / finally Block (continued) <ul><li>If no exception is thrown in a try block, all catch blocks associated with the try block are ignored and program execution resumes after the last catch block </li></ul><ul><li>If an exception is thrown in a try block, the remaining statements in the try block are ignored </li></ul><ul><ul><li>- The program searches the catch blocks in the order in which they appear after the try block and looks for an appropriate exception handler </li></ul></ul>
  12. 12. try / catch / finally Block (continued) <ul><ul><li>If the type of the thrown exception matches the parameter type in one of the catch blocks, the code of that catch block executes and the remaining catch blocks after this catch block are ignored </li></ul></ul><ul><ul><li>If there is a finally block after the last catch block, the finally block executes regardless of whether an exception occurs </li></ul></ul>
  13. 13. Order of catch Blocks <ul><li>The heading of a catch block specifies the type of exception it handles </li></ul><ul><li>A catch block can catch either all exceptions of a specific type or all types of exceptions </li></ul><ul><li>A reference variable of a superclass type can point to an object of its subclass </li></ul>
  14. 14. Order of catch Blocks (continued) <ul><li>If in the heading of a catch block you declare an exception using the class Exception , then that catch block can catch all types of exceptions because the class Exception is the superclass of all exception classes </li></ul><ul><li>In a sequence of catch blocks following a try block, a catch block declaring an exception of a subclass type should be placed before catch blocks declaring exceptions of a superclass type </li></ul>
  15. 15. Java Exception Hierarchy
  16. 16. Java Exception Hierarchy (continued)
  17. 17. Java Exception Hierarchy (continued)
  18. 18. Java Exception Hierarchy (continued)
  19. 19. Java Exception Hierarchy (continued)
  20. 20. Java’s Exception Class <ul><li>class Exception </li></ul><ul><ul><li>Subclass of class Throwable </li></ul></ul><ul><ul><li>Superclass of classes designed to handle exceptions </li></ul></ul><ul><li>Various types of exceptions </li></ul><ul><ul><li>I/O exceptions </li></ul></ul><ul><ul><li>Number format exceptions </li></ul></ul><ul><ul><li>File not found exceptions </li></ul></ul><ul><ul><li>Array index out of bounds exceptions </li></ul></ul><ul><li>Various exceptions categorized into separate classes and contained in various packages </li></ul>
  21. 21. The class Exception and its Constructors
  22. 22. Java Exception Classes
  23. 23. Java Exception Classes (continued)
  24. 24. Java Exception Classes (continued)
  25. 25. Java Exception Classes (continued)
  26. 26. Java Exception Classes (continued)
  27. 27. Java Exception Classes (continued)
  28. 28. Java Exception Classes (continued)
  29. 29. Java Exception Classes (continued)
  30. 30. Checked Exceptions <ul><li>Definition: any exception that can be recognized by the compiler </li></ul><ul><li>Examples </li></ul><ul><ul><li>FileNotFoundException s </li></ul></ul>
  31. 31. Unchecked Exceptions <ul><li>Definition: exceptions that cannot be recognized when the program compiles (must be checked for by programmer) </li></ul><ul><li>Examples </li></ul><ul><ul><li>Division by zero </li></ul></ul><ul><ul><li>Array index out of bounds </li></ul></ul><ul><li>Syntax </li></ul><ul><li>ExceptionType1 , ExceptionType2 , and so on are names of exception classes </li></ul>
  32. 32. Exceptions Example Code <ul><li>public static void exceptionMethod() </li></ul><ul><li>throws InputMismatchException, </li></ul><ul><li>FileNotFoundException </li></ul><ul><li>{ </li></ul><ul><li>//statements </li></ul><ul><li>} </li></ul><ul><li>The method exceptionMethod throws exceptions of the type InputMismatchException and FileNotFoundException </li></ul>
  33. 33. The class Exception and the Operator instanceof <ul><li>A reference of a superclass type can point to objects of its subclass </li></ul><ul><li>You can determine if a reference variable points to an object using the operator instanceof </li></ul><ul><li>You can combine catch blocks using this facility </li></ul>
  34. 34. The class Exception and the Operator instanceof try { System.out.print(&quot;Line 4: Enter the &quot; + &quot;dividend: &quot;); dividend = console.nextInt(); System.out.println(); System.out.print(&quot;Line 7: Enter the &quot; + &quot;divisor: &quot;); divisor = console.nextInt(); System.out.println(); quotient = dividend / divisor; System.out.println(&quot;Line 11: Quotient = &quot; + quotient); } catch (Exception eRef) { if (eRef instanceof ArithmeticException) System.out.println(&quot;Line 14: Exception &quot; + eRef.toString()); else if (eRef instanceof InputMismatchException) System.out.println(&quot;Line 16: Exception &quot; + eRef.toString()); }
  35. 35. Rethrowing and Throwing an Exception <ul><li>When an exception occurs in a try block, control immediately passes to one of the catch blocks; typically, a catch block does one of the following: </li></ul><ul><ul><li>Completely handles the exception </li></ul></ul><ul><ul><li>Partially processes the exception; in this case, the catch block either rethrows the same exception or throws another exception for the calling environment to handle the exception </li></ul></ul><ul><ul><li>Rethrows the same exception for the calling environment to handle the exception </li></ul></ul>
  36. 36. Rethrowing and Throwing an Exception <ul><li>Useful when: </li></ul><ul><ul><li>catch block catches exception but is unable to handle it </li></ul></ul><ul><ul><li>catch block decides exception should be handled by calling environment </li></ul></ul><ul><li>Allows programmer to provide exception handling code in one place </li></ul><ul><li>Syntax </li></ul><ul><ul><li>throw exceptionReference; </li></ul></ul>
  37. 37. Rethrowing and Throwing an Exception (continued) import java.util.*; public class RethrowExceptionExmp1 { static Scanner console = new Scanner(; public static void main(String[] args) { int number; try { number = getNumber(); System.out.println(&quot;Line 5: number = &quot; + number); } catch (InputMismatchException imeRef) { System.out.println(&quot;Line 7: Exception &quot; + imeRef.toString()); } } }
  38. 38. Rethrowing and Throwing an Exception (continued) public static int getNumber() throws InputMismatchException { int num; try { System.out.print(&quot;Line 11: Enter an “ + &quot;integer: &quot;); num = console.nextInt(); System.out.println(); return num; } catch (InputMismatchException imeRef) { throw imeRef; } } }
  39. 39. The Method printStackTrace <ul><li>Used to determine the order in which the methods were called and where the exception was handled </li></ul>
  40. 40. The Method printStackTrace (continued) import*; public class PrintStackTraceExample1 { public static void main(String[] args) { try { methodA(); } catch (Exception e) { System.out.println(e.toString() + &quot; caught in main&quot;); e.printStackTrace(); } }
  41. 41. The Method printStackTrace (continued) public static void methodA() throws Exception { methodB(); } public static void methodB() throws Exception { methodC(); } public static void methodC() throws Exception { throw new Exception(&quot;Exception generated &quot; + &quot; in method C&quot;); } }
  42. 42. The Method printStackTrace (continued) <ul><li>Sample Run </li></ul><ul><li>java.lang.Exception: Exception generated in method C caught in main </li></ul><ul><li>java.lang.Exception: Exception generated in method C </li></ul><ul><li>at PrintStackTraceExample1.methodC </li></ul><ul><li>( </li></ul><ul><li>at PrintStackTraceExample1.methodB </li></ul><ul><li>( </li></ul><ul><li>at PrintStackTraceExample1.methodA </li></ul><ul><li>( </li></ul><ul><li>at PrintStackTraceExample1.main </li></ul><ul><li>( </li></ul>
  43. 43. Exception-Handling Techniques <ul><li>Terminate program </li></ul><ul><ul><li>Output appropriate error message upon termination </li></ul></ul><ul><li>Fix error and continue </li></ul><ul><ul><li>Repeatedly get user input </li></ul></ul><ul><ul><li>Output appropriate error message until valid value is entered </li></ul></ul><ul><li>Log error and continue </li></ul><ul><ul><li>Write error messages to file and continue with program execution </li></ul></ul>
  44. 44. Creating Your Own Exception Classes <ul><li>Exception class you define extends class Exception or one of its subclasses </li></ul><ul><li>Syntax to throw your own exception object: </li></ul><ul><li>throw new ExceptionClassName(messageString); </li></ul>
  45. 45. Creating Your Own Exception Classes (continued) public class MyDivisionByZeroException extends Exception { public MyDivisionByZeroException() { super (&quot;Cannot divide by zero&quot;); } public MyDivisionByZeroException(String strMessage) { super (strMessage); } }
  46. 46. Event Handling <ul><li>Action events </li></ul><ul><ul><li>Handled by implementing interface ActionListener </li></ul></ul><ul><li>Window events </li></ul><ul><ul><li>Handled by implementing interface WindowListener </li></ul></ul><ul><li>Mouse events </li></ul><ul><ul><li>Handled by implementing interface MouseListener </li></ul></ul><ul><li>Key events </li></ul><ul><ul><li>Handled by implementing interface KeyListener </li></ul></ul>
  47. 47. Event Handling (continued) <ul><li>class WindowAdapter </li></ul><ul><ul><li>Implements interface WindowListener with empty bodies to methods </li></ul></ul><ul><li>class MouseAdapter </li></ul><ul><ul><li>Implements interface MouseListener with empty bodies to methods </li></ul></ul>
  48. 48. Registering Listeners <ul><li>Registering window listener object to GUI component </li></ul><ul><ul><li>Use method addWindowListener </li></ul></ul><ul><ul><li>Window listener object being registered is passed as parameter to method addWindowListener </li></ul></ul><ul><li>Registering mouse listener object to GUI component </li></ul><ul><ul><li>Use method addMouseListener </li></ul></ul><ul><ul><li>Mouse listener object being registered is passed as parameter to method addMouseListener </li></ul></ul>
  49. 49. Event Handling (continued)
  50. 50. Event Handling (continued)
  51. 51. Event Handling (continued)
  52. 52. Programming Example: Calculator
  53. 53. Chapter Summary <ul><li>Exception </li></ul><ul><ul><li>Definition </li></ul></ul><ul><li>Handling exceptions within a program </li></ul><ul><ul><li>try / catch / finally block </li></ul></ul><ul><ul><li>Order of catch blocks </li></ul></ul><ul><ul><li>Using try / catch blocks in a program </li></ul></ul><ul><ul><li>The class Exception and the Operator instanceof </li></ul></ul><ul><ul><li>Rethrowing and throwing an exception </li></ul></ul><ul><li>Exception </li></ul><ul><ul><li>Hierarchy </li></ul></ul><ul><ul><li>Classes </li></ul></ul>
  54. 54. Chapter Summary (continued) <ul><li>Checked and Unchecked Exceptions </li></ul><ul><li>The method printStackTrace </li></ul><ul><li>Exception handling techniques </li></ul><ul><ul><li>Terminate program </li></ul></ul><ul><ul><li>Fix error and continue </li></ul></ul><ul><ul><li>Log error and continue </li></ul></ul><ul><li>Creating your own exception classes </li></ul><ul><li>Event Handling </li></ul>