所以我得到了编译器错误,我错过了一个 return 语句,我已经查看了其他类似的问题,但我仍然对这个问题感到困惑。
public String pop()
{
try
{
if(top == -1)
{
throw new EmptyStackException("The stack is empty!");
}
String x = stack[top];
top--;
return x;
}
catch (EmptyStackException e)
{
System.out.println("The stack is empty!");
}
}
如果之前有人问过这个问题,我提前道歉,但我已经看过其他各种问题,但我似乎无法弄清楚。
最佳答案
如果捕获到异常,pop
的返回值是多少?此执行路径中没有 return 语句。这就是编译器提示的原因。
在这种情况下,pop
的调用者需要处理EmptyStackException
。不要在 pop
方法中捕获 EmptyStackException
。如果您将其定义为检查异常,则需要声明它throws EmptyStackException
。如果您不捕获它,那么该方法将始终返回值或抛出异常,这将满足编译器的要求。
请注意,可以在 catch
block 之后返回一个值。这也会满足编译器的要求,但是您会返回什么?无效的?然后调用者必须测试 null
,但调用者也可能捕获 EmptyStackException
。
关于Java 编译器错误 : Missing Return Statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29310907/