这个问题在这里已有答案:
具有异常处理程序的方法可以没有返回语句吗?!?
-Below是编辑过的代码。
public int pop() throws NullPointerException {
try{
if (a.isEmpty()){
throw new NullPointerException();
}
int x = (int)a.remove(a.size() - 1);
if (x == (int)min.get(min.size() - 1)) {
min.remove(min.size() - 1);
}
return x;
}catch(NullPointerException n) {
System.out.println("There are no elements to pop.");
}
return -1;
}
如果throw new <exception>
语句始终是通过方法体的执行路径中的最后一个语句,或者方法的返回类型是void
。
在你的代码中你可能根本无法处理EmptyStackException
。问题来自于引入最后既没有catch
或return
声明的throw
。
public int pop() {
if (a.isEmpty()){
throw new NullPointerException();
}
int x = (int) a.remove(a.size() - 1);
if (x == (int) min.get(min.size() - 1)) {
min.remove(min.size() - 1);
}
return x;
}