user1322614
user1322614

Reputation: 607

Catch custom exceptions in method.invoke()

If I use method.invoke to invoke a method that throws a custom exception A. What are the ways to catch this exception and handle it in the try catch surrounding method.invoke? The only way I can think of is to catch all Exceptions and check the Exception type;

try{
 ...
 method.invoke
 ...
} catch (A e) {

}

Upvotes: 3

Views: 1170

Answers (1)

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7302

Try:

try {
    method.invoke
} catch (InvocationTargetException e) {
   Throwable mainException = e.getCause();
   if (mainException instanceof .....) {
   }
}

InvocationTargetException is the wrapper for the exception thrown by the method.

In your case mainException will be of type A.

Upvotes: 4

Related Questions