java - 异常最终被吞噬

标签 java exception

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/

相关文章:

java - 为什么并发修改会出现在这里

exception - 为什么使用异常而不是 if...else

java - 奇怪的 xml/html 重音问题

java - 在java中创建嵌套的json对象

java - 找不到类 [de.flapdoodle.embed.process.config.IRuntimeConfig]

c++ - std::bad_alloc 被抛出的其他可能原因

java - 记录 Spring 通过 @Async 注释创建的线程抛出的 RuntimeException

java - android中的弱引用/异步任务模式

java - 如何在 Eclipse 中导出 Java 游戏?

java - 在 Google 的 Protocol Buffers 中,什么是适合异常的协议(protocol)文件/模型?