I. Exception Handling Have you used exceptions in C++? A. motivation ------------------------------------------ MOTIVATION FOR EXCEPTION HANDLING How to make a "bullet-proof" abstraction? Returning a status code: - inefficient in the normal case - users who forget aren't warned ==> insecure - checking status gets in the way ==> hard to read programs Exit the program if problems found: - inflexible ==> poor reuse Require callers to check preconditions: - doesn't work for untrusted clients ==> insecure - hard for clients to check sometimes ==> inefficient, hard to read Better: exceptions, try/catch statements ------------------------------------------ So when should you use exceptions in a design? B. exception mechanism 1. terms ------------------------------------------ EXCEPTION HANDLING MECHANISMS A convenient form of passing blocks Terms: An exception is an object that may be The code that is executed in response ------------------------------------------ C. in Java 1. exception hierarchy ------------------------------------------ EXCEPTION TYPES IN JAVA All exceptions are subclasses of Throwable Unchecked exceptions are subclasses of either Error or RuntimeException Throwable Error AWTError LinkageError ThreadDepthError VirtualMachineError OutOfMemoryError ... Exception AWT Exception ClassNotFoundException CloneNotSupportedException IOException EOFException FileNotFoundException ... RuntimeException ArithmeticException ArrayStoreException ClassCastException SecurityException IndexOutOfBoundsException NullPointerException IllegalArgumentException ... ------------------------------------------ Advantages of a hierarchy? 2. declarations in Java of what exceptions a method can throw ------------------------------------------ DECLARING EXCEPTIONS THROWN BY METHODS IN JAVA Syntax for declaring exceptions that may be thrown by a method: throws [, ] ... Example: char readChar() throws IOException { ...readByte() ... } byte readByte() throws IOException { ... } ------------------------------------------ Why? 3. throwing exceptions ------------------------------------------ THROWING AN EXCEPTION To throw an exception you have to - create an exception object, - use "throw" to throw it. Syntax: throw ; Example: throw new IOException("bad file"); ------------------------------------------ 4. catching exceptions ------------------------------------------ CATCHING AN EXCEPTION Syntax: try [catch ( ) ] ... [finally ] Example: try { } catch (IOException ioe) { System.err.println(e.getMessage()); } catch (NullPointerException npe) { System.err.println(npe); throw npe; } finally { myFile.close(); } ------------------------------------------ What else needs to be said?