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!
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?
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.
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 }
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