COSC 2011N

Thursday March 1 2001


This lecture will continue with Exceptions, continuing where we left off Tuesday.  Once again, see the following pages in the text books.

As an aside, in case you are wandering just how important error checking really is, consider the following article, describing the Therac-25 a radiation therapy treatment machine.

Time permitting, Abstract Data Types will be introduced.

A summary outlining the key points presented in class on Exceptions may be found here (postscript format).

Some other code snippets presented in class:

Defining Your Own Exception Class:

            class MyException extends Exception{
               public MyException(){}
               public MyException(String description){
                  super(description);
               }
            }

Throwing an Exception of the above type:

            throw new MyException(); or
            MyException myexc = new MyException();
            throw myexc;

The example presented in class is found below:

1. public double test(String){
2.    try{
3.       return Double.valueOf(s).doubleValue();
4.    }
5.    catch(NullPointerException ep){
6.       System.out.println(("Null Pointer ");
7.       return -2.0;
8.    }
9.    catch(NumberFormatException(ne){
10.       System.out.println("Number ");
11.       return -1.0;
12.    }
13.    finally {
14.       System.out.println("Finally ");
15.    }
16. }
Example Inputs:
Input = "1.23". When the return statement in line 3 is executed, the finally clause runs before the method actually returns. The output is "Finally" and the return value is 1.23.

Input = "XX". The method call in line3 throws a NumberFormatException that is caught in line 8. The output is "Number Finally" and the method returns -1.0.

Input is the special null value. The method call in line 3 throws a NullPointerException that is caught in line 4. The output is "NullPointer Finally" and the return value is -2.0.

If the method call in line 3 throws an exception that isn't caught, the finally clause is still executed, but the exception has to be handled by the calling method. Notice that in spite of executing the method a return statement in lines 3, 7 or 11, the method doesn't actually return until
the finally clause has been executed. Furthermore, the finally clause can replace the return value. For example if the finally clause reads:
finally{
   System.out.println("Finally ");
   Return -3.0;
}
the return value of this method is always -3.0. e.g. the return call in the finally block will override the return value in the catch blocks.  A transfer of contro, statement (e.g. break, continue, return and throw) in the finally block will override any transfer of control statements which may be in a catch block.