Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Catching an exception from a reflectively called constructor

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){}
like image 631
Numeron Avatar asked Aug 01 '12 03:08

Numeron


1 Answers

The exception will be thrown wrapped in an InvocationTargetException. Catch that and have a look at the cause.

like image 68
user207421 Avatar answered Sep 30 '22 17:09

user207421