Chapter Goals Chapter 15 • To learn how to throw exceptions • To be able to design your own exception Exception Handling classes • To understand the difference between checked and unchecked exceptions • To learn how to catch exceptions • To know when and where to catch an exception Error Handling Error Handling • Traditional approach: Method returns error • Instead of programming for success code x.doSomething() • Problem: Forget to check for error code you would always be programming for failure: Failure notification may go undetected • Problem: Calling method may not be able to if (!x.doSomething()) return false; do anything about failure Program must fail too and let its caller worry about it Many method calls would need to be checked Continued… Throwing Exceptions Throwing Exceptions • Exceptions: • No need to store exception object in a Can't be overlooked variable: Sent directly to an exception handler–not just caller of failed method throw new IllegalArgumentException("Amount exceeds balance"); • Throw an exception object to signal an exceptional condition • When an exception is thrown, method terminates immediately • Example: IllegalArgumentException: Execution continues with an exception handler illegal parameter value IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; Continued… 1
Example Hierarchy of Exception Classes public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; } . . . } Figure 1: The Hierarchy of Exception Classes Syntax 15.1: Throwing an Exception Self Check 1. How should you modify the deposit method to ensure that the balance is never throw exceptionObject ; negative? Example: throw new IllegalArgumentException(); 2. Suppose you construct a new bank account object with a zero balance and then call Purpose: To throw an exception and transfer control to a handler for this withdraw(10) . What is the value of exception type balance afterwards? Answers Checked and Unchecked Exceptions 1. Throw an exception if the amount being • Two types of exceptions: deposited is less than zero. Checked • The compiler checks that you don't ignore them 2. The balance is still zero because the last • Due to external circumstances that the statement of the withdraw method was programmer cannot prevent never executed. • Majority occur when dealing with input and output • For example, IOException 2
Checked and Unchecked Exceptions Checked and Unchecked Exceptions • Two types of exceptions: • Categories aren't perfect: Unchecked: Scanner.nextInt throws unchecked InputMismatchException • Extend the class RuntimeException or Error Programmer cannot prevent users from entering • They are the programmer's fault incorrect input • Examples of runtime exceptions: This choice makes the class easy to use for beginning NumberFormatException programmers IllegalArgumentException NullPointerException • Deal with checked exceptions principally when programming with files and streams • Example of error: OutOfMemoryError Continued… Checked and Unchecked Exceptions Checked and Unchecked Exceptions • For example, use a Scanner to read a file • Two choices: Handle the exception String filename = . . .; Tell compiler that you want method to be terminated FileReader reader = new FileReader(filename); when the exception occurs Scanner in = new Scanner(reader); • Use throws specifier so method can throw a checked exception But, FileReader constructor can throw a FileNotFoundException public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); . . . } Continued… Checked and Unchecked Exceptions Syntax 15.2: Exception Specification • For multiple exceptions: accessSpecifier returnType methodName (parameterType parameterName, . . .) public void read(String filename) throws ExceptionClass , ExceptionClass , . . . throws IOException, ClassNotFoundException Example: • Keep in mind inheritance hierarchy: public void read(BufferedReader in) throws IOException If method can throw an IOException and Purpose: FileNotFoundException , only use To indicate the checked exceptions that this method can throw IOException • Better to declare exception than to handle it incompetently 3
Self Check Answer 3. Suppose a method calls the FileReader 3. The specification throws IOException is constructor and the read method of the sufficient because FileReader class, which can throw an FileNotFoundException is a subclass of IOException . Which throws specification IOException . should you use? 4. Because programmers should simply check 4. Why is a NullPointerException not a for null pointers instead of trying to handle checked exception? a NullPointerException . Catching Exceptions Catching Exceptions • Example: • Install an exception handler with try/catch try statement { String filename = . . .; • try block contains statements that may FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); cause an exception String input = in.next(); int value = Integer.parseInt(input); • catch clause contains handler for an . . . exception type } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); Continued… } Catching Exceptions Catching Exceptions • catch (IOException exception) block • Statements in try block are executed exception contains reference to the exception • If no exceptions occur, catch clauses are object that was thrown skipped catch clause can analyze object to find out more details • If exception of matching type occurs, exception.printStackTrace(): printout of execution jumps to catch clause chain of method calls that lead to exception • If exception of another type occurs, it is thrown until it is caught by another try block Continued… 4
Syntax 15.3: General Try Block Syntax 15.3: General Try Block Example: try try { { statement System.out.println("How old are you?"); statement int age = in.nextInt(); . . . } System.out.println("Next year, you'll be " + (age + 1)); catch ( ExceptionClass exceptionObject ) } { catch (InputMismatchException exception) statement { statement exception.printStackTrace(); . . . } } catch ( ExceptionClass exceptionObject ) Purpose: { statement To execute one or more statements that may generate exceptions. statement If an exception occurs and it matches one of the catch clauses, . . . execute the first one that matches. If no exception occurs, or an Continued… } exception is thrown that doesn't match any catch clause, then skip . . . the catch clauses. Self Check Answers 5. The FileReader constructor succeeds, and 5. Suppose the file with the given file name in is constructed. Then the call in.next() exists and has no contents. Trace the flow of execution in the try block in this section. throws a NoSuchElementException , and the try block is aborted. None of the catch 6. Is there a difference between catching clauses match, so none are executed. If none checked and unchecked exceptions? of the enclosing method calls catch the exception, the program terminates. Continued… The finally clause Answers 6. No–you catch both exception types in the • Exception terminates current method same way, as you can see from the code • Danger: Can skip over essential code example on page 558. Recall that I OException is a checked exception and • Example: NumberFormatException is an unchecked exception. reader = new FileReader(filename); Scanner in = new Scanner(reader); readData(in); reader.close(); // May never get here 5
The finally clause The finally clause • Must execute reader.close() even if FileReader reader = new FileReader(filename); exception happens try { • Use finally clause for code that must be Scanner in = new Scanner(reader); readData(in); executed "no matter what" } finally { reader.close(); // if an exception occurs, finally clause // is also executed before exception is // passed to its handler } The finally clause Syntax 15.4: The finally clause • Executed when try block is exited in any of try { three ways: statement statement After last statement of try block . . . After last statement of catch clause, if this try block } finally caught an exception { When an exception was thrown in try block and not statement statement caught . . . } Continued… • Recommendation: don't mix catch and finally clauses in same try block Syntax 15.4: The finally clause Self Check 7. Why was the reader variable declared Example: FileReader reader = new FileReader(filename); outside the try block? try { 8. Suppose the file with the given name does readData(reader); } not exist. Trace the flow of execution of the finally { code segment in this section. reader.close(); } Purpose: To ensure that the statements in the finally clause are executed whether or not the statements in the try block throw an exception. 6
Recommend
More recommend