I create an object using reflection. Depending on the actual object, the constructor may have a throws declaration for a particular custom exception, and I can catch its importance.
Unfortunately, when I try to add an exception to the catch of a try block, which includes a reflective construct, the code will not compile because:
"Unreachable catch block. This exception is never thrown from an attempt to an operator body."
I understand that catching an Exception base class will work and realize that this is normal for my code. However, this may not always be the case, since other other exceptions may apply to other objects in the future, and using the instance inside the catch and re-throw everything else seems inelegant.
Is there any way to report that this exception can be thrown so that I can catch it?
edit: Invalid code on request. Does not compile due to 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){}
source share