加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

为什么Java堆栈跟踪只返回finally块中的失败?

发布时间:2020-12-15 08:25:36 所属栏目:Java 来源:网络整理
导读:我写了一些自动化测试,我使用的语法如下 – try { // Test case steps and validations} finally { // Clean up related to test} 注意:这没有catch块,因为我的测试不期望异常. 如果try和finally块中的测试失败,则只在控制台上返回finally的失败而不是try.
我写了一些自动化测试,我使用的语法如下 –

try { 
   // Test case steps and validations
} finally { 
   // Clean up related to test
}

注意:这没有catch块,因为我的测试不期望异常.

如果try和finally块中的测试失败,则只在控制台上返回finally的失败而不是try.这里的简单示例(此处使用TestNG进行断言) –

try {
    Assert.assertEquals(true,false,"Boolean values did not match");
} finally {
    Assert.assertEquals(100,10,"Integer values did not match");
}

在这种情况下,仅返回最终失败的详细信息.

这无助于识别查看控制台的测试的实际失败.

我想了解为什么Java不会在控制台上返回两个故障细节,这可以帮助用户在第一眼看到故障原因.

解决方法

抛出异常可以观察到同样的事情:

try {
    throw new RuntimeException("Message 1");
} finally {
    throw new RuntimeException("Message 2");
}

这里只打印消息2:

Exception in thread "main" java.lang.RuntimeException: Message 2

这是因为当最终抛出异常时,try中的任何异常都被“丢弃并遗忘”:

JLS第14.20.2节

  • If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement,
    then the finally block is executed. Then there is a choice:

    • If the finally block completes normally,then the try statement completes abruptly because of a throw of the value V.

    • 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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读