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.
Time permitting, Abstract Data Types will be introduced.
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){Example Inputs:
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. }
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.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 untilInput = "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.
finally{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.
System.out.println("Finally ");
Return -3.0;
}