References: Jacquie Barker, Beginning Java Objects ; Rick Mercer, Computing Fundamentals With Java; Wirfs - Brock et. al., Martin Fowler, OOPSLA 99 Tutorial ; internet notes; notes:h. Conrad Cunningham 11/13/2003 IT350 1 Exceptions are error conditions -- not bugs a bug is a defect in the code an error condition is a predictable failure that occurs under certain circumstances Exceptions are the way a program can handle gracefully an error that would cause a crash. 11/13/2003 IT350 2 The Java language provides many exception handlers for programmer errors Java runtime system detects an exceptional event an Exception object is constructed containing info about exception type runtime system throws an exception runtime system looks for code to handle the exception if no handler found, program terminates 11/13/2003 IT350 3 1
Example: Java throws an exception when an invalid number is entered public class HandleException public static void main ( String[] args ) TextReader keyboard = new TextReader(); System.out.println ( Enter a number: ); String numberstring = keyboard.readword(); double number = Double.parseDouble ( numberstring ); System.out.println( numberstring + stored in number as + number; ); 11/13/2003 IT350 4 Dialogue when number entered is not valid: Enter a number: 35o Exception in thread main java.lang.numberformatexception: 35o atjava.lang.floatingdecimal.readjavaformatstring (FloatingDecimal.java:1176) at java.lang.double.parsedouble(double.java.184) at HandleException.main(HandleException.java.io) Java displays a stack of method calls; main is the bottom of the stack the exception occurred in the method on the top 11/13/2003 IT350 5 We don t usually want the program to terminate, but rather to proceed with some alternative action in the event of an exception. So we write code to catch the exception A try block is wrapped around the code being executed. It is followed immediately by a catch block, which contains code that executes in the event of an error. We also specify in the catch block what type of exception is being thrown 11/13/2003 IT350 6 2
Using try/catch to Handle Exceptions public class HandleException public static void main ( String[] args ) TextReader keyboard = new TextReader(); System.out.println ( Enter a number: ); String numberasstring = keyboard. readword (); double number; try number = Double. parsedouble( numberasstring ); catch (NumberFormatException nfe) System.out. println(numberasstring + is not a valid number ); System.out. println( Setting number to -1.0 ); number = -1.0; System.out.println( numberasstring + stored in number as + number; ); 11/13/2003 IT350 7 Runtime Exceptions You must know when a method might throw an exception and what type of exception it throws. Read the documentation to find out! /** From Double class: * Return a floating-point number represented by the String * argument; If numberasstring does not represent a valid * number, this method will throw a number format * exception. */ public static double parsedouble(string numberasstring) throws NumberFormatException 11/13/2003 IT350 8 Handling an I/O Exception If an I/O connection fails, Java throws an IOException. This is the method for a URL connection: public URLConnection() throws IOException Here s the usage: java.net.url url = new java.net.url( http://www.sice.umkc.edu/ ) java.net.urlconnection conn; try conn= url.openconnection(); catch (java.io.ioexception e ) //an error has occurred; log an error, print a message or //throw another exception 11/13/2003 IT350 9 3
Unchecked Exceptions The parsedouble method does not catch the exception!! If the programmer does not put the method call in a try block and explicitly catch the exception, the program simply terminates (as shown in earlier example). This is one of the unchecked exceptions: one that doesn t need to be handled many unchecked exception classes extend the RuntimeException class. 11/13/2003 IT350 10 Handling exceptions in extending classes is optional Exceptions Classes Hierarchy Object Throwable Exception RuntimeException ClassNotFoundException IOException ArithmeticException FileNotFoundException...EOFException... NumberFormatException ArrayIndexOutOfBoundsException NullPointerException... 11/13/2003 IT350 11 Writing a Method That Throws an Exception public void deposit (double anamount) throws IllegalArgumentException if (anamount <= 0.0) throw new IllegalArgumentException(); balance = balance + anamount; The keyword throw must be followed by an instance of a class that extends Throwable. Because Exception extends Throwable, an instance of any Exception class can be thrown. 11/13/2003 IT350 12 4
Multiple Catch Statements There may be multiple categories of exceptions that you want to catch Each category is a separate catch block try //some code catch (NullPointerException e1) catch (IllegalArgumentException e2) catch (Exception e3) //This is a catch -all -- catches any type of exception that can be thrown finally //this code is executed even if an exception did not occur //commonly used to clean up internal state (like closing a file) 11/13/2003 IT350 13 5