Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between handling exceptions by catch block directly parent class and subclasses

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?

like image 710
stackoverflow Avatar asked Mar 14 '16 12:03

stackoverflow


2 Answers

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.

like image 175
Eran Avatar answered Nov 27 '22 18:11

Eran


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

like image 20
Jordi Castilla Avatar answered Nov 27 '22 19:11

Jordi Castilla