Chapter 9: Exceptions For error/problem situations Exception classes –ArithmeticException, IOException, etc. –checked exceptions try blocks –catch statements –propagation –throws clause –finally
Dealing with Errors - Exceptions Example: if (n > 0) avg = total / n; else avg = ??? (what to do) idea: identify situations where error occurs –if error occurs, “throw” an exception –have routines to “catch” (deal with) exception
Exception Classes Lots! java.lang.ArithmeticException java.lang.IndexOutofBoundsException (parent of java.lang.ArrayIndexOutofBoundsException java.lang.StringIndexOutofBoundsException) java.lang.NegativeArraySizeException java.lang.NullPointerException java.io.IOException java.io.InterrruptedIOException java.io.EOFException java.io.FileNotFoundException...
Some Methods with Exceptions IllegalArgumentException Choice String getItem(int index) - if index out of range void select(int index) - same problem Container void add(Component c) - trying to add c to itself Dialog Dialog(Frame parent) - parent is null Label void setAlignment(int a) - a not Label.CENTER, etc. TextArea void setColumns(int c) - if c negative void setRows(int r) - if r negative
More Exceptions NumberFormatException Double static double valueOf(String s) - s not double - also for float, int, long NullPointerException Choice void addItem(String s) - string is null almost all String methods that take String args etc.
Dealing with Exceptions Ignore: will cause program to terminate Write code so they don’t occur: sometimes difficult Idea: recognize when they occur and add ways to deal with them
Try Blocks Format: try { // code with possible exception } Section of code you think may raise an exception If an exception occurs within a try block, the block terminates Java then looks for a “catch” statement following try block dealing with exception
Catch Statement Format: catch (ExceptionClass name) { // } Immediately follows try May be more than one –if > 1, first to match is used Matched by class of exception thrown name attached to instance associated with exception
Exception Example try { avg = total / n; // go on to use avg in output // if exception raised these statements skipped } catch (ArithmeticException e) { // indicate there is a problem }
Multiple Catch Statements If more than one catch, first to match Exception class used Be careful to list them in the order you want them to apply try { } catch (Exception e) { // catches anything } catch (ArithmeticException e) { // pointless }
Propagating Exceptions If no case matching exception raised after try, exception propagates until caught –may propagate out of methods (sometimes) try { // exception thrown } catch (DifferentExceptionType e) { // not caught } catch (NeededExceptionType e) { // caught here }
Throws Clause Methods may have attached throws clause –Method header: Type methName(args) throws EType1, EType2, … Important for “checked” exceptions –checked exceptions may not propagate out of method unless included in throws clause –samples: IOExceptions, your own exceptions –generally, any subclass of RunTimeExceptions not checked
Using Your Own Exceptions Two ctors: ExceptionClass() ExceptionClass(String message) - associate message with exception (used when caught) Throwing: throw myExceptionInstance; Remember to see if the Class you are using is checked
void showEmployee(Employee[] bees, int MaxEmp, int index) { try { if ((index = MaxEmp)) throw new ArrayIndexOutOfBounds(“No employee with number” + String.valueOf(index)); // go ahead and show bees[index] } catch (ArrayIndexOutOfBounds e) { // dump out message }
Finally May add finally statement after last catch, finally is always executed whether catch used or not Format: finally { // stuff here } Good for cleanup code (deallocating temporary space set aside with new, etc.)