Reputation: 23537
Say I have a method foo() declared below.
public class Foo
{
public static void foo() {throw new UnsupportedOperationException();}
}
Then I have code that invoked the method using reflection:
Foo.class.getMethod("foo").invoke();
This would throw InvocationTargetException
rather than the UnsupportedOperationException
that is actually thrown in the method.
How do I retrieve the real exception (ie., the UnsupportedOperationException) with Java's reflection?
Upvotes: 3
Views: 112
Reputation: 3679
try{
// do your invoke
}
catch ( InvocationTargetException e)
{
try
{
throw e.getCause ( ) ;
}
catch ( IllegalArgumentException e )
{
// method exception
}
catch ( NullPointerException e )
{
//method exception
}
}
http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html
Upvotes: 0
Reputation: 35587
You are getting that InvocationTargetException
due to refection invocation. Handle that Exception
too.
Upvotes: 0
Reputation: 280174
The javadoc for InvocationTargetException
states
InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor.
Just call InvocationTargetException#getCause()
to get the wrapped exception (or getTargetException()
if you want to be old-school).
Upvotes: 6