Why does the Java stack trace only return failures in the finally block?

I have written some automated tests, and the syntax i use is as follows –

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

Note: there is no catch block because my test does not expect exceptions

If the test in the try and finally blocks fails, only the finally failure is returned on the console instead of try Here's a simple example (where TestNG is used for assertion) –

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

In this case, only the details of the final failure are returned

This does not help identify the actual failure of the test viewing the console

I want to know why Java does not return two fault details on the console, which can help users see the cause of the fault at the first sight

Solution

Throwing an exception can observe the same thing:

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

Only message 2 is printed here:

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

This is because when an exception is finally thrown, any exception in the try is "discarded and forgotten":

JLS section 14.20 Section 2

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>