Will an assertion error be caught by in a catch block for java exception?

JavaJunitTry CatchAssert

Java Problem Overview


Code:-

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

If the assert statements fails, I would like to capture the error in the catch block. I am trying with the above code and its not happening.

Will the assertion error be caught by in a catch block for java exception?

Java Solutions


Solution 1 - Java

You have almost answered your own question. Your catch block will not catch the AssertionError that the Assert throws if it fails, because it is an Error (or, more specifically, it extends java.lang.Error). See the docs for more information on this. Your catch block only catches Throwable objects that extend java.lang.Exception

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

catch (AssertionError e) {
...

However, as others have mentioned, this is a very unusual way to use assertions - they should usually pass and if they fail it is very unusual for you to want to carry on program execution. That's why the failure throws an Error rather than an Exception. You can read more about (not) catching Error in this question.

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

NB if you are testing unit-test helper code, like a matcher, it might make sense to catch the AssertionError.

Solution 2 - Java

If you want to catch both Exception and Error instances use:

...
catch (Throwable t)
{
...
}

Since both Exception and Error extend Throwable.

Solution 3 - Java

Well, I believe you are using JUnit for writing your tests. In that case, you should not catch your Assert.assertEquals() because they should pass for normal test execution. If it throws any exception, it means that your code is not performing as it should.

Solution 4 - Java

If you want to catch the errors in that way you need something like the following:

if (num == 1 || num == 2) {
    throw new Exception();
}

You could create your own exception class and pass in the message you want.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGaletView Question on Stackoverflow
Solution 1 - JavaJ Richard SnapeView Answer on Stackoverflow
Solution 2 - JavawilmolView Answer on Stackoverflow
Solution 3 - JavaAakashView Answer on Stackoverflow
Solution 4 - JavaSpaceCowboyView Answer on Stackoverflow