I am creating a object using reflection. Depending on the actual object being constructed, the constructor might have a throws declaration for a particular custom exception and its important I can catch this.
Unfortunately, when I attempt to add the exception to catches of the try block that encompasses the reflective construction, the code will not compile because:
"Unreachable catch block. This exception is never thrown from the try statement body"
I realise that catching the base class Exception would work, and infact that is ok for my code. However, it might not always be the case, since other different exceptions may apply for other objects in the future and using instanceof inside of a catch and re-throwing everything else seems inelegant.
Is there a way to signal that this exception might be thrown, so that I can catch it specifically?
edit: Some code as requested. Does not compile because of above.
try{
Constructor<? extends Thing> constructor = getClassType().getDeclaredConstructor(SomeParameter.class);
Thing thing = constructor.newInstance(new SomeParameter());
}
catch(FoobarException e){
//new Thing(SomeParameter p) might throw this
}
catch(ReflectiveOperationException | IllegalArgumentException | SecurityException e){}
The exception will be thrown wrapped in an InvocationTargetException
. Catch that and have a look at the cause.
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