更新时间:2022-05-10 08:22:56
pop
如果捕获到异常?在此执行路径中没有返回语句。这是为什么编译器抱怨。
What is the return value of pop
if the exception is caught? There is no return statement in this execution path. That is why the compiler is complaining.
在这种情况下, pop
的调用者需要处理 EmptyStackException
。不要在 pop
方法中捕获 EmptyStackException
。如果将它定义为已检查的异常,则需要声明它抛出EmptyStackException
。如果你不捕获它,那么方法将总是返回值或抛出异常,这将满足编译器。
In this case, the caller of pop
needs to handle the EmptyStackException
. Don't catch EmptyStackException
inside the pop
method. You'll need to declare that it throws EmptyStackException
if you defined it to be a checked exception. If you don't catch it, then the method will always return the value or throw the exception, and that will satisfy the compiler.
注意,可能返回一个值在 catch
块之后。这也将满足编译器,但你会返回什么?空值?然后调用者必须测试 null
,但调用者也可以捕获 EmptyStackException
。
Note that it's possible to return a value after the catch
block. This will also satisfy the compiler, but what would you return? Null? Then the caller must test for null
, but the caller might as well catch the EmptyStackException
.