static int retIntExc() throws Exception{
int result = 1;
try {
result = 2;
throw new IOException("Exception rised.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
result = 3;
} finally {
return result;
}
}
我的一个 friend 是 .NET 开发人员,目前正在迁移到 Java,他问我以下有关此源的问题。理论上这必须 throw IOException("Exception rise.")
并且整个方法 retIntExc()
必须 throws Exception
。但是没有任何反应,该方法返回 2。
我没有测试他的例子,但我认为这不是预期的行为。
编辑:感谢所有回答。有些人忽略了方法名为 retIntExc
的事实,这意味着这只是一些测试/实验示例,显示了 throw/catch 机制的问题。我不需要“修复”,我需要解释为什么会这样。
最佳答案
这就是为什么不能从 C# 中的 finally block 返回的原因:)
不过,这绝对是 Java 语言规范中规定的行为。它在 section 14.20.2 中指定.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).
返回是突然完成的一个例子;如果 finally
block 抛出异常,也会突然完成,丢失原始异常。
上面的引用来自这组嵌套的要点,省略了此处不适用的选项:
- If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
- If the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the finally block is executed. Then there is a choice:
- If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).
关于java - 异常最终被吞噬,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4711064/