Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch custom exceptions in method.invoke()

Tags:

java

exception

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) {

}
like image 264
user1322614 Avatar asked Jun 21 '26 01:06

user1322614


1 Answers

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.

like image 69
Amir Pashazadeh Avatar answered Jun 23 '26 13:06

Amir Pashazadeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!