Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 933
Galet Avatar asked Apr 16 '15 10:04

Galet


People also ask

How do you catch an assertion error in catch block?

In order to catch the assertion error, we need to declare the assertion statement in the try block with the second expression being the message to be displayed and catch the assertion error in the catch block.

Can we catch error in catch block in Java?

Yes, we can catch an error. The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the throw statement.

Is assertion error an exception Java?

AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails. If x is not greater than 10 then you will get runtime exception saying AssertionError. Wrong. Errors are not Exceptions.

Which errors Cannot be handled by catch block?

As is documented, try/catch blocks can't handle StackOverflowException and OutOfMemoryException.


2 Answers

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.

like image 171
J Richard Snape Avatar answered Sep 30 '22 01:09

J Richard Snape


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

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

Since both Exception and Error extend Throwable.

like image 31
wilmol Avatar answered Sep 30 '22 00:09

wilmol