Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check whether a certain exception type was the cause (of a cause, etc ...) in a nested exception?

I am writing some JUnit tests that verify that an exception of type MyCustomException is thrown. However, this exception is wrapped in other exceptions a number of times, e.g. in an InvocationTargetException, which in turn is wrapped in a RuntimeException.

What's the best way to determine whether MyCustomException somehow caused the exception that I actually catch? I would like to do something like this (see underlined):

 try {     doSomethingPotentiallyExceptional();     fail("Expected an exception."); } catch (RuntimeException e) {      if (!e.wasCausedBy(MyCustomException.class)         fail("Expected a different kind of exception."); } 

I would like to avoid calling getCause() a few "layers" deep, and similar ugly work-arounds. Is there a nicer way?

(Apparently, Spring has NestedRuntimeException.contains(Class), which does what I want - but I'm not using Spring.)

CLOSED: OK, I guess there's really no getting around a utility method :-) Thanks to everybody who replied!

like image 793
Yang Meyer Avatar asked Mar 04 '09 13:03

Yang Meyer


People also ask

How do you check exceptions in Python?

exc_info() function – This function returns a tuple of three values that give information about the exception that is currently being handled. Related: How to print an error in Python?

How compiler is knowing that which type of exception is occurring?

Compiler does not know what type of exception it just take that instance and then find out the its type using reflection then print the stack's trace on console.


1 Answers

If you are using Apache Commons Lang, then you can use the following:

(1) When the cause should be exactly of the specified type

if (ExceptionUtils.indexOfThrowable(exception, ExpectedException.class) != -1) {     // exception is or has a cause of type ExpectedException.class } 

(2) When the cause should be either of the specified type or its subclass type

if (ExceptionUtils.indexOfType(exception, ExpectedException.class) != -1) {     // exception is or has a cause of type ExpectedException.class or its subclass } 
like image 121
Patrick Boos Avatar answered Sep 20 '22 23:09

Patrick Boos