Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (11.4k points)

Well, I've tried to understand and read what could cause it but I just can't get it:

I have this somewhere in my code:

 try{
 ..
 m.invoke(testObject);
 ..
 } catch(AssertionError e){
 ...
 } catch(Exception e){
 ..
 }


Thing is that, when it tries to invoke some method it throws  InvocationTargetException instead of some other expected exception (specifically ArrayIndexOutOfBoundsException). As I actually know what method is invoked I went straight to this method code and added a try-catch block for the line that suppose to throw  ArrayIndexOutOfBoundsException and it really threw ArrayIndexOutOfBoundsException as expected. Yet when going up it somehow changes to InvocationTargetException and in the code above catch(Exception e) e is InvocationTargetException and not ArrayIndexOutOfBoundsException as expected.

What could cause such a behavior or how can I check such a thing?

1 Answer

0 votes
by (32.3k points)

It seems to me like you've added an extra level of abstraction by calling the method with reflection. Any exception in an InvocationTargetException is wrapped in an exception layer, which actually tells you the difference between an exception caused by a failure in the reflection call and a failure within the method called.

Just do one thing,  unwrap the cause within the InvocationTargetException and you'll get to the original one.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 18, 2021 in Java by dante07 (13.1k points)

Browse Categories

...