Exception Handling

396 views

Published on

Chapter 9

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
396
On SlideShare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
12
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • We can increase our programs’ reliability and robustness if we catch the exceptions ourselves using error recovery routines we develop.
    One way to do this is to wrap the statements that may throw an exception with the try-catch control statement.
  • Consider the given example. What would happen if the user enters a value such as the text 'ten' instead of 10? The parseInt method cannot convert such an input to an internal numerical format. This type of error is called an exception, and it will result in displaying an error message such as the one shown here. We say the parseInt method has thrown a NumberFormatException.
  • The classes shown here are some of the more common classes in the Throwable class hierarchy. We will be seeing most of the Exception and its subclasses shown here in the later modules.
  • This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement.
  • This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement.
  • This illustrates how the control flows when there is an exception and when there is no exception.
    In the case when no statements in the try block throw an exception, then the catch block is skipped and execution continues with the next statement following the try-catch statement.
    If any one of the statements throws an exception, the statements in the catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  • In the previous example, we simply displayed a fixed error message. We can get display a more generic error message by using the getMessage or printStrackTrace methods. We will experiment with these methods in the lab.
  • In this example, we see two statements in the try block that can potentially throw exceptions. The parseInt method throws a NumberFormatException while the get method throws an ArrayIndexOutOfBoundsException when the argument id is outside the range of valid values.
  • Here's how the control flows when there are multiple catch blocks.
    In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement.
    If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  • Here's how the control flows when there are multiple catch blocks.
    In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement.
    If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  • Here's how the control flows when there are multiple catch blocks.
    In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement.
    If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  • The finally block is not used often in introductory level programs, but we will introduce them here for the sake of complete coverage of the topic. For example, suppose we open a communication channel from our Java program to a remote web server to exchange data. If the data exchange is successfully completed in the try block, then we close the communication channel and finish the operation. If the data exchange is interrupted for some reason, an exception is thrown and the operation is aborted. In this case also, we need to close the communication channel, because leaving the channel open by one application blocks other applications from using it. The code to close the communication channel should therefore be placed in the finally block.
  • Here's how the control flows when there are multiple catch blocks and the finally block.
    In the case when no statements in the try block throw an exception, then all catch blocks are skipped, but the statements in the finally block are executed. Execution continues with the next statement following the try-catch statement.
    If any one of the statements throws an exception, the statements in the matching catch block are executed first and the statements in the finally block are executed next. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  • Using the try-catch statement is the first way to handle the exceptions. The second way is to propagate the thrown exception back to the caller of the method. The method that includes the statement that calls our method must either catch it or propagate it back to their caller.
  • It is possible to throw an exception from our own method.
  • We say a method throws an exception directly when the method includes the throw statement. Otherwise, a method is throwing an exception indirectly.
  • This illustration shows a sequence of method calls among the exception throwers.
    Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher.
    The call sequence is traced by using a stack.
  • Callers of a method that can throw a checked exception must include the try-catch statement in the method body or the throws clause in the header.
  • It is optional for callers of a method that can throw runtime exceptions to include the try-catch statement in the method body or the throws clause in the header.
  • Exception Handling

    1. 1. Exceptions
    2. 2. Objectives  After you have read and studied this chapter, you should be able to Improve the reliability of code by incorporating exception-handling. Implement the try-catch blocks for catching and handling exceptions. Write methods that propagate exceptions. Distinguish the checked and unchecked, or runtime, exceptions.
    3. 3. Definition  An exception represents an error condition that can occur during the normal course of program execution.  Examples Division by zero Trying to open an input file that does not exist An array index that goes out of bounds
    4. 4. Java’s Mechanism of Exception Handling  When an exception occurs, an object of a particular exception class can be created and thrown.  The exception-handling routine can then be executed to catch & handle the exception object; we say the thrown exception is caught.  The normal sequence of flow is terminated if the exception object is thrown.
    5. 5. Exception thrown Scanner scan = new Scanner(System.in); int num = 0; System.out.print(“Enter an integer>”); num = scan.nextInt(); System.out.println(“The number you entered is “ +num); Enter an integer> three Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at ExceptionTest.main(ExceptionTest.java:11) Error message for invalid input
    6. 6. Java’s Mechanism of Exception Handling (continued) Java provides a number of exception classes to effectively handle certain common exceptions such as division by zero, invalid input, and file not found Example:  When a Scanner object is used to input data into a program, any invalid input errors are handled using the class InputMismatchException  When a division by zero exception occurs, the program creates an object of the class ArithmeticException
    7. 7. Exception Types  All types of thrown exception objects are instances of the Throwable class or its subclasses.  Serious errors are represented by instances of the Error class or its subclasses.  Exceptional cases that common applications should handle are represented by instances of the Exception class or its subclasses.
    8. 8. Throwable Hierarchy  There are over 60 classes in the hierarchy.
    9. 9. Catching an Exception To catch an exception: •Put code that might throw an exception inside a try{} block. •Put code that handles the exception inside a catch{} block. Use try{} and catch{} block try { // statements, some of which might // throw an exception } catch ( SomeExceptionType ex ) { // statements to handle this // type of exception }
    10. 10. Catching an Exception Scanner scan = new Scanner(System.in); int num = 0; try { System.out.print(“Enter an integer>”); num = scan.nextInt(); } catch (InputMismatchException e){ System.out.println(“Invalid input! Please enter digits only"); } System.out.println(“The number you entered is “ +num); try catch
    11. 11. try-catch Control Flow
    12. 12. Getting Information  There are two methods we can call to get information about the thrown exception: getMessage printStackTracetry { . . . } catch (NumberFormatException e){ System.out.println(e.getMessage()); System.out.println(e.printStackTrace()); }
    13. 13. Multiple catch Blocks  A single try-catch statement can include multiple catch blocks, one for each type of exception. try { . . . age = Integer.parseInt(inputStr); . . . val = cal.get(id); . . . } catch (NumberFormatException e){ . . . } catch (ArrayIndexOutOfBoundsException e){ . . . }
    14. 14. Multiple catch Control Flow -Only one catch{} block gets control (the first block that matches the type of the exception ). -If no catch{} block matches the exception, none is picked (just as if there were no try{} block.)
    15. 15. Multiple catch Control Flow •The most specific exception types should appear first in the structure, followed by the more general exception types. A child class should appear before any of its ancestors. If class A is not an ancestor or descendant of class B, then it doesn't matter which appears first. Eg. the following is wrong: try { ... } catch (Exception ex ) { . . . } catch (ArithmeticException ex ) { . . . }
    16. 16. Multiple catch Control Flow Question: Is this ok?: try { ... } catch (NumberFormatException ex ) { . . . } catch (ArithmeticException ex ) { . . . }
    17. 17. The finally Block  There are situations where we need to take certain actions regardless of whether an exception is thrown or not.  We place statements that must be executed regardless of exceptions in the finally block. try { // statements, some of which might // throw an exception } catch ( SomeExceptionType ex ) { // statements to handle this // type of exception } catch ( AnotherExceptionType ex ) { // statements to handle this // type of exception } finally { // statements which will execute no matter // how the try block was exited. }
    18. 18. try-catch-finally Control Flow
    19. 19. Propagating Exceptions  Instead of catching a thrown exception by using the try-catch statement, we can propagate the thrown exception back to the caller of our method.  The method header includes the reserved word throws. public int getAge( ) throws NumberFormatException { . . . int age = Integer.parseInt(inputStr); . . . return age; }
    20. 20. Throwing Exceptions  We can write a method that throws an exception directly, i.e., this method is the origin of the exception.  Use the throw reserved to create a new instance of the Exception or its subclasses.  The method header includes the reserved word throws. public void doWork(int num) throws Exception { . . . if (num != val) throw new Exception("Invalid val"); . . . }
    21. 21. Exception Thrower  When a method may throw an exception, either directly or indirectly, we call the method an exception thrower.  Every exception thrower must be one of two types:  catcher.  propagator.
    22. 22. Types of Exception Throwers  An exception catcher is an exception thrower that includes a matching catch block for the thrown exception.  An exception propagator does not contain a matching catch block.  A method may be a catcher of one exception and a propagator of another.
    23. 23. Sample Call Sequence
    24. 24. Checked vs. Unchecked Exception  There are two types of exceptions:  Checked.  Unchecked.  A checked exception is an exception that is checked at compile time, so it must be handled.  An unchecked exception is not checked at compile time, so no need to handle (optional).  unchecked exception include Error and RuntimeException and their subclasses.  checked exception include Exception
    25. 25. Different Handling Rules  When calling a method that can throw checked exceptions use the try-catch statement and place the call in the try block, or modify the method header to include the appropriate throws clause.  When calling a method that can throw runtime exceptions, it is optional to use the try-catch statement or modify the method header to include a throws clause.
    26. 26. Handling Checked Exceptions
    27. 27. Handling Runtime Exceptions

    ×