Consider the following code
public void myMethod1() {
try {
this.getClass().getMethod("myMethod").invoke(this);
} catch (Exception e) {
throw e;
}
}
public void myMethod1_fixed() throws Exception {
try {
this.getClass().getMethod("myMethod").invoke(this);
} catch (Exception e) {
throw e;
}
}
public void myMethod2() {
try {
this.getClass().getMethod("myMethod").invoke(this);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
} catch (Exception e) {
throw e;
}
}
myMethod1()
was complaining about not handling the Exception e
being thrown, which I understand because Exception
is checked exception and you are forced to handle it, hence the myMethod1_fixed()
added throws Exception
and it was happy.
Now with myMethod2()
it also throws Exception e
, but it was happy even though there was no throws Exception
, meaning Exception
is unchecked?
As explained in Rethrowing Exceptions with More Inclusive Type Checking, the compiler considers which actual exception may occur, when you catch and re-throw exceptions, since Java 7.
So in
you already catched all checked exception in the previous
catch
clause, and only unchecked exception are possible.Note that you must not modify the variable
e
for this to work.