Goal: To learn how to handle error situations with a modern technique call Exceptions.
Tutorial
Consider this C program and its old style of reporting errors via return code or call-by-reference parameter: except.c
Here is a modern object-oriented way of reporting errors via the Exception class: API: Exception.java
and the corresponding C program written in Java using Exceptions: Except.java
and also a tutorial.
The two key points are:
A UML hierarchy of Exception inheritance: ex4a.pdf
That is, programmers can develop their own Exceptions, just like those for SQL or AWT. These exceptions can be thrown and caught at various points in the code.
Here is a design for an example program:
method | action | catch | throw |
main(args[0]) | call a(i) | ArrayIndexOutOfBoundsException | |
NumberFormatException | |||
a(i) | call b(i) | MySubException | |
MyException | |||
b(i) | call c(i) | MyOtherException | MyException |
c(i) | i=0 | MyException | |
i=1 | MySubException | ||
i=99 | MyOtherException | ||
default | return i*i |
and the program itself: Except1.java
The above is tested with this demo
Assignment
For the first part, you are given this UML hiearchy of Exception inheritance: ex4b.pdf
and the following design:
method | action | catch | throw |
main(args[0]) | ArrayIndexOutOfBoundsException | ||
NumberFormatException | |||
call x(i) | E2 | ||
E1 | |||
x(i) | i=1..10 | OK | |
i=11..20 | E1 | ||
default: call y(i) | E3 | E1 | |
y(i) | i=21..30 | OK | |
i=31..40 | E2 | ||
default | E3 |
Code E.java, only class E needs to be public, the Exceptions can just be included in the source.
Put a testing main in E.java similar to the one in Except1.java.
The output should look like demo1
Note the messages printed by demo1 follow these rules:
Now you're ready for the second part of the assignment.
Copy your Stack.java from Ex1: cp ../ex1/Stack.java .
Recall the Person class from Ex1: Person.java
Modify your Stack.java to handle the error situations where:
1. push() is performed on a full stack
2. pop() is performed on an empty stack
Create your own type of Exception, and be sure to test the pop().
Turn-In: E.java, including commented-out listing of the resultant output. Stack.java, also with output.