CSC152 2005F, Class 16: Exceptions Admin: * Perlmutter talk today at 4:30, refreshments at 4:15. E.C. * Gaub concert tomorrow at 11:00 in Herrick. E.C. * Cram talk Friday at noon: "Natural selection on two flower-color polymorphisms in /Clarkia xantiana ssp. parviflora/. E.C. * Homework still not graded * Reading for Friday not yet available * Exam 1 to be distributed Friday Overview: * Quick review of exceptions * Q&A * Lab. Notes on Exceptions * Programs or parts of programs are going to fail. * Why might a call to Integer.parseInt(str) fail? * str might represent a value too big, e.g., "12323342342344522334242363476345641218786876876" * If the string doesn't have just digits, the call is likely to fail e.g., "two" * Other reasons ... * How do I design my program to accomodate errors? * Two basic strategies: * Check parameters before calling the potentially erroneous proc. if (helper.checkForOnlyDigits(str) && helper.verifyNotTooLarge(str)) { i = Integer.parseInt(str); } * Require procedures to signal an error by returning a special value Consider "assoc" in Scheme * Given an association list (list of key/value pairs) and a key, return either (a) key/value pair with the same key (b) #f, if the key does not appear * The calling procedure must now check the result to see if it's "okay" * Checking preconditions is (a) inefficient and (b) a pain in the "pick a part of your body" * Checking preconditions is also not always possible * Checking return values is (a) inefficient and (b) less painful, but stil painfil" * No common form for return values * Evidence the programmers plan to check for errors and never do Java's solution (based on past designs in other languages) like the special return values. This solution is called "exceptions" When you fail, don't return to the procedure call, but return elsewhere i = Integer.parseInt(str); bleh; blah; blou; RETURN HERE WHEN anything above fails More efficient than checking return values; uniform; Java goes a step further and *requires* you to handle errors Normal form of all of this: * How to say "This procedure may fail" public int parseInteger(String str) throws Exception // This procedure may fail Generally "throws Exception" * How to say "Whoops, this procedure has failed" throw new Exception("explanation"); * How to say "return here when ... fails" try { // Code that may fail } catch (Exception e) { // Recover from the code that may fail } * HOw to say "if this code fails, my procedure fails" public int myProcedure() throws Exception { ... i = Integer.parseInt(str); ... --- DO THE LAB WITH A PARTNER }