-2

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?

Holger
  • 285,553
  • 42
  • 434
  • 765
user1589188
  • 5,316
  • 17
  • 67
  • 130
  • 2
    The compiler knows that any checked exception would have been caught in the previous block, so it must be a `RuntimeException`. – shmosel Jul 17 '17 at 09:14
  • Wow that was quick. Thanks for pointing me to the other question with the answer. So my understanding to the definition of checked and unchecked exceptions is still correct, just that since JAVA 7 the compiler was clever enough to identify the real exception type. But anyway, no need to neg. – user1589188 Jul 17 '17 at 09:21

1 Answers1

2

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

try {
    this.getClass().getMethod("myMethod").invoke(this);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
} catch (Exception e) {
    throw e;
}

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.

Holger
  • 285,553
  • 42
  • 434
  • 765