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?
I usually ask myself these questions:
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.
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());
}
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