Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching several exceptions and rethrowing a general exception

Tags:

java

exception

I'm using reflection to add some data to a private variable inside a class from a third-party library. Along the way there are about four different Exceptions that can be thrown; all of them are related to reflection, and all of them are very unlikely to occur. I'm hardcoding the name of the class and variable involved. I'm unlikely to receive any class not found or field not found errors, unless the library gets upgraded some day and has changed significantly.

I'd rather not declare all four of these exceptions for my caller to handle. He's likely to never see them. I'd like to just catch all of these and throw another exception to say "A Java reflection error has occured; it is likely that the library has been upgraded and changed in a way incompatible with this method." Is there a standard Java Exception I can throw that indicates just a general reflection error? Should I define my own? Or would it be best to just declare that this method can throw all of the possible reflection exceptions?

like image 994
skiphoppy Avatar asked Jan 26 '09 16:01

skiphoppy


2 Answers

I usually ask myself these questions:

  • Can whomever calls this method handle these different exception types differently?
  • ...Or would they treat them all the same?
  • Can the caller/user even recover from this error?

If the calling code is likely to treat all four of these exceptions the same (as an unrecoverable error), then it absolutely makes sense to capture each of them and re-throw a more general (single) exception. If you do, make sure you attach the generated exception as an inner exception, just to help any debugging or troubleshooting on the other end.

like image 116
matt b Avatar answered Oct 10 '22 08:10

matt b


You can turn all the Exceptions into an AssertionError if you never expect them to occur. InvocationTargetException can be unwrapped if you want to deal with a specific exception. If you want to throw the actual exception thrown by the method rather than InvocationTargetException you can use this trick, but it may be more confusing than useful

} catch (InvocationTargetException e) {
    // Throw any exception in the current thread (even if it is a checked exception)
    Thread.currentThread().stop(e.getCause());
}
like image 40
Peter Lawrey Avatar answered Oct 10 '22 08:10

Peter Lawrey