COMP 121 Week 5: Exceptions and Exception Handling Objectives To learn how to throw exceptions To understand the difference between checked and unchecked exceptions To learn how to catch exceptions To know when and where to catch an exception To learn how to create your own exception classes Error Handling Traditional approach -- Method returns a value to indicate success or failure The calling method may not check return value Failure notification may go undetected The calling method may not be able to do anything about failure Calling method must fail, too, and let its caller worry about it Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Error Handling Instead of programming for success: x.doSomething(); You are always programming for failure: if (!x.doSomething()) return false; Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Java Solution: Exceptions Exceptions Can't be overlooked Are sent directly to an exception handler – not just the caller of failed method To signal an exceptional condition, use throw statement to throw an exception Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Exception Example public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Throwing Exceptions No need to store exception object in a variable: throw new IllegalArgumentException("Amount exceeds balance"); When an exception is thrown, the method that threw the exception terminates immediately Execution continues with an exception handler Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Hierarchy of Exception Classes Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Checked and Unchecked Exceptions Checked Exceptions Compiler checks that you take care of a checked exception if you call a method that throws one Due to external circumstances that the programmer cannot prevent Majority occur when dealing with input and output A checked exception is not a subclass of RuntimeException or Error Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Checked and Unchecked Exceptions Unchecked Exceptions Compiler does not check that you take care of an unchecked exception if you call a method that throws one Due to circumstances that the programmer can prevent An unchecked exception is a subclass of RuntimeException or Error Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Checked and Unchecked Exceptions Categories aren't perfect: Scanner.nextInt throws unchecked InputMismatchException Programmer cannot prevent users from entering incorrect input Majority of checked exceptions deal with input and output (files and streams) Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Checked and Unchecked Exceptions For example, use a Scanner to read a file String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); FileReader constructor can throw a FileNotFoundException (checked exception) Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Options for Checked Exceptions Two choices: Handle the exception Tell compiler that you want the method to be terminated when the exception occurs Your method doesn’t handle the exception, so it throws the exception up to its caller Use throws specifier when method can throw a checked exception public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); . . . } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Options for Checked Exceptions A single method can throw multiple exceptions Use throws with exception separated by commas: public void read(String filename) throws IOException, ClassNotFoundException Keep in mind the inheritance hierarchy: method can throw an IOException and FileNotFoundException, only use IOException (superclass of FileNotFoundException) If Better to throw an exception you don’t know how to handle than handle it incorrectly or incompletely Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Catching Exceptions Install an exception handler with try/catch statement try block contains statements that may cause an exception catch clause contains the handler for a certain type of exception May have multiple catch clauses for the different types of exceptions Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Example of Catching Exceptions try { String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input); . . . } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. General try/catch Syntax try { statement statement . . . } catch (ExceptionClass exceptionObject) { statement statement . . . } catch (ExceptionClass exceptionObject) { statement statement . . . } . . . Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Catching Exceptions Statements in try block are executed If no exceptions occur, catch clauses are skipped If an exception matching a caught type occurs, execution jumps to catch clause that matches After the catch block is executed, the method continues with the code after the entire try/catch statement If exception that doesn’t match a caught type occurs, it is thrown until it is caught by another try block (try blocks can be nested) If an exception is not caught, it eventually will terminate the program Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Catch Block catch (ExceptionClass exception) ExceptionClass is the actual type (class name) of the exception being caught exception contains reference to the exception object that was thrown catch clause can analyze object to find out more details exception.printStackTrace() Prints out the chain of method calls that led to the exception exception.getMessage() Retrieves the message string from the exception Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Flow of Control with try/catch try { // beginning of try block Foo f = myobj.doSomething(); // doSomething may throw an exception int x = f.getNum(); // will get here only if doSomething succeeded } // end of try block catch (Exception ex) { // beginning of catch System.out.println(“doSomething failed”); // displayed if doSomething failed ex.printStackTrace(); // displays stack } // end of catch block System.out.printlin(“End of try/catch”); // No exception or caught exception Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Question: How do you know what exceptions may be thrown? Answer: Compile your code, and the compiler will let you know (if it is a checked exception) Read the javadoc! Installed file:///c:/Program%20Files/Java/jdk1.6.0/docs/api/index.html Also when Java was installed on the system available on the Internet http://java.sun.com/javase/6/docs/api/ Javadoc for Java Platform SE 6 Question: What exception(s) may be thrown when a FileReader object is constructed? Answer: FileNotFoundException Question:What is the superclass of FileNotFoundException? Answer: IOException The finally clause Exception terminates current method May cause the JVM to skip over essential code Example: PrintWriter out = new PrintWriter(filename); writeData(out); out.close(); // May never get here Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. The finally clause Use optional finally clause for code that must be executed no matter what Once a try block is entered, the statements in the finally clause are guaranteed to execute whether an exception is thrown or not Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. The finally clause PrintWriter out = new try { writeData(out); } finally { out.close(); // // // PrintWriter(filename); if an exception occurs, finally clause is executed before exception is passed to its handler. Also executed // if no exception occurs. } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. The finally clause try { statement statement . . . } finally { statement statement . . . } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. The finally clause Executed when try block is exited in any of three ways: last statement of try block After last statement of catch clause that caught the exception, if one was thrown When an exception was thrown in try block and was not caught After Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Designing Your Own Exception Classes You can design your own exception types– subclasses of Exception or RuntimeException if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of “ + balance); } It is an unchecked exception–programmer could have avoided it by calling getBalance and checking first Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Designing Your Own Exception Classes In your exception class Extend RuntimeException or one of its subclasses Supply two constructors 1. 2. Default constructor A constructor that accepts a message string describing reason for exception Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Designing Your Own Exception Classes public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException(String message) { super(message); } } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Guidelines for Exceptions To signal an exceptional condition, use the throw statement to throw an exception object Add a throws specifier to any method that can throw a checked exception It is better to declare that a method throws a checked exception than to handle it poorly Do not “squelch” exceptions by catching the exception and then doing nothing To handle an exception, put the code that can cause the exception inside a try block, and put the handler code inside the catch Throw the most specific exception type you can Only catch an exception if you know how to handle it Design your own exception classes as subclasses of Exception or RuntimeException only if the standard exception types don’t adequately describe the error Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Summary An exception is used to signal an error condition When an exception is thrown, the current method terminates immediately There are two kinds of exceptions: checked and unchecked The compiler checks that your program handles checked exceptions Unchecked exceptions extend the class RuntimeException or Error Statements that can cause an exception can be put inside a try block A catch clause is used to handle the exception A finally clause is used for code that is guaranteed to execute, whether or not an exception is thrown Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons. Any Questions?