栈的pop方法,我们这样写:
int pop(){
return array[top--];
}
然后我看jdk源代码,写法相当于:
int pop(){
if(top<0)throw new ArrayIndexOutOfBoundsException();
return array[top--];
}
然而即使没有增加的那句话,当top等于-1时,Java运行环境仍然会自动帮我们抛出ArrayIndexOutOfBoundsException,那么还要自己手动抛出异常干嘛?
自己手动抛出异常,提供更多的主动和灵活处理的可能,java运行环境抛出异常,只有程序运行时才会发现。
你抛出异常给你的调用者,java抛出异常给你。不是一回事。
ArrayIndexOutOfBoundsException异常数组越界了。你的代码如下:
int pop(){
return array[top--];
}
好像没有手动抛出异常!!!