/*
1、SUN提供的JDK内置的异常肯定是不够的用的。在实际的开发中,有很多业务,
这些业务出现异常之后,JDK中都是没有的。和业务挂钩的。那么异常类我们
程序员可以自己定义吗?
可以。
2、Java中怎么自定义异常呢?
两步:
第一步:编写一个类继承Exception或者RuntimeException.
第二步:提供两个构造方法,一个无参数的,一个带有String参数的。
死记硬背。
*/
public class MyException extends Exception{
// 编译时异常
public MyException(){
}
public MyException(String s){
super(s);
}
}
/*
public class MyException extends RuntimeException{ // 运行时异常
}
*/
public class Mystack {
public static void main(String[] args) {
// 创建栈对象
Mystack stack = new Mystack();
// 压栈
try {
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
// 这里栈满了
stack.push(new Object());
} catch (Mystackces e) {
// 输出异常的简单信息。
System.out.println(e.getMessage());
}
// 弹栈
try {
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
// 弹栈失败
stack.pop();
} catch (Mystackces e) {
System.out.println(e.getMessage());
}
}
private Object[] elements;
private int index;
public Mystack() {
this.elements = new Object[10];
this.index = -1;
}
public void push(Object obj) throws Mystackces {
if(this.index>=this.elements.length-1){
throw new Mystackces("栈已满!!");
}
this.index++;
this.elements[index] = obj;
System.out.println("成功 index = "+index);
}
public Object pop() throws Mystackces {
if(index == -1){
throw new Mystackces("栈空!!!");
}
// System.out.print("弹栈" + " " + elements[index] + "元素成功,");
// 栈帧向下移动一位。
return elements[index--];
// System.out.println("栈帧指向" + index);
// return index;
}
public Object[] getElements() {
return elements;
}
public void setElements(Object[] elements) {
this.elements = elements;
}
}
必须写下面的!!!
public class Mystackces extends Exception{
public Mystackces(){
}
public Mystackces(String s){
super(s);
}
}