Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 522
meriton Avatar asked Sep 29 '22 17:09

meriton


1 Answers

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:

  • https://bugs.eclipse.org/bugs/show_bug.cgi?id=429430

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.

like image 116
Lukas Eder Avatar answered Nov 02 '22 10:11

Lukas Eder