-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?

2
  • 2
    The compiler knows that any checked exception would have been caught in the previous block, so it must be a RuntimeException. Commented Jul 17, 2017 at 9: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. Commented Jul 17, 2017 at 9:21

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! So it was a clever compiler's doing, not Exception became unchecked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.