Extended ExampleA flexible numberic stack. package numericstack;
import java.lang.reflect.Array;
import simplestack.*;
public class NumericStack {
public static final int STKSIZE = 4;
protected Object stack;
protected int top = 0;
public NumericStack(String className)
throws ClassNotFoundException {
stack =
Array.newInstance(Class.forName(className), STKSIZE);
}
public void push(Object obj)
throws StackOverflowException, IllegalArgumentException {
try {
Array.set(stack,top++,obj);
} catch (ArrayIndexOutOfBoundsException e) {
top = STKSIZE;
throw new StackOverflowException();
}
}
public Object pop() throws StackUnderflowException {
try {
return Array.get(stack,--top);
} catch (Exception e) {
top = 0;
throw new StackUnderflowException(e.getMessage());
}
}
public int top() {
return top;
}
}import simplestack.StackOverflowException;
import numericstack.NumericStack;
/**
* @author jack
*/
public class TestIt {
public static void main(String[] args) {
try {
NumericStack stack = new NumericStack("java.lang.Integer");
stack.push(new Integer(1));
stack.push(new Integer(2));
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (StackOverflowException e) {
System.out.println(e);
} catch (IllegalArgumentException e) {
System.out.println(e);
}
}
}Exercise: modify TestIt.java to generate each of the exception type caugth. You may test each exception one at a time. |