LECTURE NOVEMBER 3 2004 ASSIGNMENTS Fri 11/5 CodeLab #9 Mon 11/8 Assignment 3 Code - Questions about Assignment 3? What? - useful methods inherited from Throwable Why? - get information about thrown exceptions When? - call inside the catch block How? - instance methods - getMessage() - print the message associated with exception - what this is can vary - printStackTrace() - prints the message we see when the program crashes because we didn't handle the exception Example: String s = "hi"; s = null; try { s.compareTo("hello"); } catch (NullPointerException npe) { System.out.println(npe.getMessage()); npe.printStackTrace(); } Output: null java.lang.NullPointerException at NullExcepEg.main(NullExcepEg.java:7) What? - Throwable subclasses - Exception: conditions that ordinary programs should catch - Error: conditions too serious for ordinary programs to catch What? - Error How? - too serious to catch - not required to handle them What? - types of exceptions - *checked exception* - *unchecked exception* How? - unchecked exceptions are descended from class RuntimeException PROPAGATING EXCEPTIONS What? - *exception thrower* - directly: contains a throw statement - indirectly: calls a method that directly or indirectly thorws an exception What? - *exception catcher* What? - *exception propagator* When? - checked exceptions - required - compiler-enforced - optional for runtime exceptions How? - signature states exception types propagated - reserved word throws - syntax ( {} Why? - exception is caused because a condition set by a client is violated - propagate to client Example: AgeInputVer4 What? - method that is both How? - catches some exception but propagates a different one Example: void d() { if (cond) { throw new Exception(); } } void e() throws Exception { try { d(); } catch (Exception e) { } if (cond) { throw new Exception(); } } What? - stack trace How? - system keeps track of method calls using a stack What? - exception catching resolution How? - system goes down the stack, looking for a catch block What? - make exception catcher propagate the caught exception How? - syntax: try { // exception throwing statement: direct or indirect } catch (Exception e) { // handle throw e; // propagate } PROGRAMMER-DEFINED EXCEPTIONS Why? - existing exceptions don't provide enough information to exception handlers What? - define our own exception classes How? class extends Exception {} - extend Exception because want our exceptions to be checked - otherwise, why bother making them, if we can't force clients to use them? Example: AgeInputException Ch8TestAgeInputVer5