Exception Handling Geoff Holmes Week 5 problems Handling Throwing Catching Multiple exceptions Finally clause Examples Week 5 Problems Write a program to read a file of filenames representing images (*.jpg). Store the filenames in an array and iteratively display the contents of each file (see Section 18.4). Exercise 16.1 (Exception handling) Exercise 14.2 – read a file and count the number of lines, words and characters (covers Utility classes) Exercise 19.3 – collection classes, will start to do either Tuesday or Friday. Department of Computer Science 2 Handling Errors In exceptional circumstances (eg bad data input) we use Java’s exception handling system. Where do errors come from? User input errors Device errors (printer turned off) Physical limits (disk full, out of memory) Code errors – array indexes, pop an empty stack. Normal error handling is to return (-1) but this doesn’t always work. Also, it isn’t OOP to return a number to mark an error state. Department of Computer Science 3 Motivation Exceptions are events that disrupt normal program flow; e.g. processing a file: Ask the user for filename Open file Read contents Do something with contents Close file Lots of potential problems (file not found, not readable, …) Java supports strong distinction between normal and abnormal program flow Department of Computer Science 4 Exception hierarchy Throwable Error LinkageError VirtualMachineError … Exception IOException RuntimeException • ClassCastException • … … Every exception is an instance of a subclass of Throwable Programmers are not forced to deal with Error and RuntimeException cases (too common) Department of Computer Science 5 Throwing your own Suppose you have a problem with premature EOF when reading data. You know it is an IOException and find EOFException: String readData(BufferedReader in) throws EOFException { While (…) { If (n < len) throw new EOFException( ); … } Department of Computer Science 6 Can give EOFException a string String problem = “Should be “ + len + “ but is “ + n; throw new EOFException(problem); So for exisiting exceptions we: Find the appropriate class Make an object of that class Throw it Department of Computer Science 7 No exception fits? class FileFormatException extends IOException { public FileFormatException( ) { } public FileFormatException(String problem) { super(problem); } } String readData(BufferedReader in) throws FileFormatException { While (…) { If (n < len) throw new FileFormatException( ); … } Department of Computer Science 8 Catching Exceptions Use a try/catch block to catch exceptions: try { code more code more code } catch (ExceptionType e) { handler for this type } Department of Computer Science 9 What happens? If any code in the try block throws an exception of the class specified in the catch block then the program skips the remaining code and executes the handler code. If none of the code throws an exception then the catch block is skipped. Department of Computer Science 10 Example 1 – ExceptionTest Try to pop an empty stack! Department of Computer Science 11 Rules for passing or treating Catch those exceptions that you know how to handle Propagate those that you do not! Department of Computer Science 12 Catching any exception – ExceptionMethods catch (Exception e) { System.out.println(“caught an exception”); } To get better info on the error we can use: 1. e.getMessage( ) 2. e.toString( ) 3. e.printStackTrace( ) Department of Computer Science 13 Multiple Exceptions Try { code that might contain many exceptions } catch (MalformedURLException e1) { code to handle bad URLs } catch (UnknownHostException e2) { code to handle unknown hosts } catch (IOEXception e3) { code to handle all other IO problems } Department of Computer Science 14 Book example try { File fd1 = new File(name); File fd2 = new File(name); processFile(fd1,fd2); fd1.close(); fd2.close(); } catch (FileNotFoundException e) { System.err.println(“Cannot find file “ + e); } catch (FileOpenFailed e) { System.err.println(“Cannot open file “ + e); } Department of Computer Science 15 Finally clause Optional last clause in a try/catch block Will always be executed, no matter what exceptions have been thrown and handled: try { throw new EOFException(); } catch (EOFException e) { e.printStackTrace(); throw new ClassCastException(); } finally { System.out.println(“Finally”); } Will even execute when “return” is used! Department of Computer Science 16 Final note Graphics g = image.getGraphics( ); try { code that might throw exceptions } catch (IOException e) { done = true; } finally { g.dispose( ); } 1. Suppose no exceptions thrown 2. Exception thrown of type IOException 3. Exception thrown not of type IOException Department of Computer Science 17