自定义异常在写框架的时候常会用到,那么,我们如何自定义一个异常呢?
比如我定义一个栈溢出异常
public class StackOverflowException extends Exception{
public StackOverflowException(){
super();
}
public StackOverflowException(String message){
super(message);
}
}
然后定义了一个栈
public class Stack<T> {
public static final int STACK_SIZE = 1000;
Object data[] = new Object[STACK_SIZE];
int top = 0;
public boolean isFull(){
if(top == STACK_SIZE){
return true;
}else return false;
}
public boolean isEmpty(){
if(top == 0) return true;
else return false;
}
public void push(T e) throws StackOverflowException{
if(!isFull())data[++top] = e;
else throw new StackOverflowException("栈向上溢出");
}
public T pop() throws StackOverflowException{
T t = null;
if(!isEmpty()){
t = (T)data[top--];
return t;
}else{
throw new StackOverflowException("栈向下溢出");
}
}
}
使用这个栈
public class Test{
public static void main(String[] args) {
Stack<Person> stack = new Stack<Person>();
Person p1 = new Person(1);
Person p2 = new Person(2);
try {
stack.push(p1);
stack.push(p2);
while(!stack.isEmpty()){
System.out.println(stack.pop().getAge());
}
} catch (StackOverflowException e) {
e.printStackTrace();
}
}
}
输出结果
2
1
总结
由此可知,自定义一个异常,我们只需要继承与Exception类或者其他异常类即可,然后重载构造方法即可。
当然上面没有发生异常,当如果连续压栈1001个数据的时候,就会出现栈向上溢出的异常。