meriton
meriton

Reputation: 70564

Lambda type inference infers an exception type not thrown by the lambda

The code

class TestException extends Exception {

}

interface Task<E extends Exception> {
    void call() throws E;
}

public class TaskPerformer {

    /** performs a task in the proper context, rethrowing any exceptions the task declares */
    private <E extends Exception> void perform(Task<E> task) throws E {
        beforeTask();
        try {
            task.call();
        } finally {
            afterTask();
        }
    }

    private void afterTask() {
        // implementation elided (does not matter)
    }

    private void beforeTask() {
        // implementation elided (does not matter)
    }

    public static void main(String[] args) {
        new TaskPerformer().perform(() -> {       // compilation error
            try {
                throw new TestException();
            } catch (TestException e) {
                return;
            }
        });
    }
}

is rejected by the eclipse compiler with the error

Unhandled exception type TestException

at the first line of main, even though the lambda expression handles this exception (right?).

Is this a compiler bug, or am I overlooking something?

Upvotes: 5

Views: 591

Answers (1)

Lukas Eder
Lukas Eder

Reputation: 220842

There had been tons of bugs in recent releases of Eclipse (and also javac, IntelliJ, etc.) with respect to lambda expressions and type inference. Just today, I've registered 460511, 460515, and 460517. For instance, there had been quite a few fixes around the combination of lambda expressions and exception types in this issue alone:

I don't have the issue you're experiencing in Eclipse 4.5.0 M5 (nor with javac build 1.8.0_40-ea-b21), so I'm taking a bet that this is a bug, and it has been fixed.

As a general rule of thumb, if you're using Java 8 with Eclipse, do upgrade to the latest Mars (4.5.0) milestone. Always. It'll save you dozens of headaches.

Upvotes: 4

Related Questions