I have the following Java code
import org.testng.annotations.Test;
@Test
public void testException(){
try{
Assert.assertEquals(1,2);
} catch(Exception e) {
e.printStackTrace();
}
}
When the test is run, the assertion fails and exception is printed as standard output and the TestNG shows the test result as FAILED.
If I catch the same exception using
catch(AssertionError e){
e.printStackTrace();
}
the exception is printed as error output and the TestNG shows the test result as PASSED. In both cases exception is handled, but what is the difference here?
AssertionError
is not a sub-class of Exception
(it's a sub-class of Error
), so the first snippet, with the catch(Exception e)
handler, doesn't catch it. Therefore the test result is FAILED.
The second snippet catches the exception, so as far a TestNG
is concerned, no exceptions occurred in the test of testException()
and the result is PASSED.
Because AssertionError
is child of Throwable
and Error
, not from Exception
:
java.lang.Object
java.lang.Throwable
java.lang.Error
java.lang.AssertionError
So the line:
catch(Exception e){
Won't catch it in the case of error. What you can do is:
catch(Error e){
or
catch(Throwable t){
But you must be careful as explained here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With