CSC152 2006S, Class 15: Exceptions Admin: * Readings: Static Variables and Constants ; Javadoc * Homework: Finish the lab and turn in your work * Stop working on homework after an hour or two! Don't stay up until 3 a.m.! * EC for Aaron Overview: * Programmatic strategies for dealing with errors * Java's solution: Exceptions * Lab About Errors and Problems * Think about procedures from the perspective of * The person who wrote the procedure: callee; developer * The person who is calling the procedure: caller; client * Part of the negotiation is dealing with potential errors * Strategy one: Preconditions: "The client must ensure a, b, and c before the developer guarantees that the procedure works correctly." * Not all preconditions can be checked (or easily checked) If I am writing long expt(long x, int n), what preconditions might I have? * Parameters are correct types. (Checked by Java.) * N is non-negative. (Easy to check.) * x^n is representable as a long * Precondition checking can be needlessly expensive * Same example: Needlessly repeating work * Strategy two: Special return values to indicate something went wrong (assoc key assoc-list) -> Given a list of key/value pairs, returns the first one with a matching key, returns false if there is no match (define assoc (lambda (key lst) (cond ((null lst) ...) ((eqv? key (car (car lst))) (car lst)) (assoc key (cdr lst))))) Client of assoc is supposed to check the return value (let ((stuff (assoc 'tapesamu (phone-lists)))) (if (stuff) (tell (cdr stuff) "Wake up sleepyhead"))) * Problems: * In a typed language like Java, it may be hard to decide what the "indication of error" should be. For example, what should readInt return when the user is a bozo? * Evidence that programmers rarely check the return value. * Strategy three: Exceptions Permit the developer to say * "This is what can go wrong" * "Whoops something went wrong" Requires the client to say * When this potential error happens, do this instead of what I would normally do Client syntax in Java try { ...; } catch (Exception e) { ...; } If everything in the try succeeds, skips the catch block. If something in teh try fails, immediately exits (skipping subsequent operations) and executes the catch block. Developer syntax in Java "There are times my code may fail" public static methodName(...) throws Exception { ... } "Whoops, it did fail" throw new Exception("The user gave really stupid input");