1

Given a class with static method and throw some exception

class Foo {
    public static void doThis() throws CannotDoThisException {
        //do something
    }
}

I am using the following reflection to invoke the doThis method

public class Bar {
    Class c = Class.forName("Foo");
    Method m = c.getDeclaredMethod("doThis",null);
    try {
        m.invoke(null,null);
    } catch (CannotDoThisException e) {
       //Compiler says this is unreachable block.
    }
}

How can I catch the exception CannotDoThisException?

Shuyou
  • 81
  • 1
  • 5

1 Answers1

0

The reason you can't catch that exception is that Method::invoke (javadoc) won't throw it !

If the method that you are calling via invoke throws any exception, the reflection layer catches it and then creates and throws an InvocationTargetException (javadoc) with the original exception as the exception's cause.

So this is what you need to do:

public class Bar {
    Class c = Class.forName("Foo");
    Method m = c.getDeclaredMethod("doThis",null);
    try {
        m.invoke(null,null);
    } catch (InvocationTargetException e) {
       if (e.getCause() instanceof CannotDoThisException) {
           // do something about it
       } else {
           // do something else
           // if the `cause` exception is unchecked you could rethrow it.
       }
    }
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thank you very much for the quick answer! I searched but couldn't find it. Without knowing the keyword of InvocationTargetException, it is kind of difficult to find the duplicates. Also thanks to Dave pointing out the duplicate. – Shuyou Mar 31 '19 at 00:03