5

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?

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
stackoverflow
  • 2,134
  • 3
  • 19
  • 35

2 Answers2

6

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

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

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109