Will an assertion error be found in the catch block of the Java exception?

Code:-

try {
    Assert.assertEquals("1","2");
} catch (Exception e) {
    System.out.println("I am in error block");
}

If the assert statement fails, I want to catch the error in the catch block I'm trying to use the above code instead of what happens

Will it be caught by assertion errors in the catch block of Java exceptions?

Solution

You almost answered your own question Since it is an error (or more specifically, it extends Java. Lang. error), your catch block will not catch the assertionerror caused by asset thrown by asset See the docs for more information Your catch block captures only extended Java Throwable object of lang.exception

If you really want to catch it – you need to use it

catch (AssertionError e) {
...

However, since others have stated, this is a very unusual way to use assertions - usually should pass, and if they fail, it is very unusual for you to want to execute the program This is why failure raises errors rather than exceptions You can read more about (not) catching errors in this question

Are you sure you don't just want a test – if (variablename = = "1")?

Note that if you are testing unit test helper code, like matchers, it may make sense to capture assertionerrors

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
分享
二维码
< <上一篇
下一篇>>