What is the difference between exception handling by catch block directly by 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 executed, the statement fails, and the exception is printed as standard output, and TestNG shows the test result as FAILED.

If I catch the same exception using

 catch(AssertionError e){ e.printStackTrace(); } 

the exception is printed as an error output, and TestNG shows the test result as PASSED. In both cases the exception is handled, but what is the difference here?

+5
source share
2 answers

AssertionError not a subclass of Exception (it is a subclass of the Error class), so the first fragment with a catch(Exception e) handler does not catch it. Therefore, the test result is CORRECT.

The second snippet will catch an exception, so before TestNG there were no exceptions in the testException() test, and the result was PASSED.

+6
source

Because AssertionError is a child of Throwable and Error , and not from Exception :

 java.lang.Object java.lang.Throwable java.lang.Error java.lang.AssertionError 

So the line:

 catch(Exception e){ 

Do not catch it in case of error. What you can do is:

 catch(Error e){ 

or

 catch(Throwable t){ 

But you have to be careful as it explains

+2
source

Source: https://habr.com/ru/post/1245010/


All Articles