Java - selecting an exception from a constructor with a reflective name

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){} 
+4
source share
2 answers

The exception will be wrapped in an InvocationTargetException . Catch this and look at the reason.

+11
source

Is there any way to report that this exception can be thrown so that I can catch it?

No.

Because in this case, any exception thrown by the constructor will be caught, and InvocationTargetException will be thrown in its place. This is explained using javadoc as follows:

" Throws : [...] InvocationTargetException - if the base constructor throws an exception."

(Note that it states an β€œexception”, so this applies to both checked and unverified exceptions created by the constructor.)

So actually the compiler is telling the truth in this compilation error. The checked exception that you tried to catch cannot propagate at this point. Indeed, the JLS accessibility rules state that the code is definitely unreachable ... hence a compilation error.

+2
source

All Articles