Search code examples
javajava-7unhandled-exception

Java 7 Checked exception rules


I know the rules about checked exceptions, but I can't quite work out this puzzler. Why does thfe second method not compile, but the first one does? The error is "Unhandled exception type Exception" on the last throws statement. I can understand why I get this error, but I don't understand why the first method is ok, it should have the same problem?!

Both eclipse and intellij show the same error.

import java.util.concurrent.Callable;

public class ThrowableWeirdness {

    public void doWithMetrics(String name, Runnable runnable) {

        try {
            runnable.run();
        } catch (Throwable e) {
            System.out.printf(name + ".failed");
            throw e;
        }
    }

    public <RET> RET doWithMetrics(String name, Callable<RET> runnable) {

        try {
            return runnable.call();
        } catch (Throwable e) {
            System.out.printf(name + ".failed");
            throw e; // Compilation error on this line: unhandled exception
        }
    }
}

Can you explain the difference between the two methods?


Solution

    • In the first case, runnable.run does not throw any checked Exception, so your try/catch and rethrow are not inferred to throw anything checked, hence it compiles
    • In your second case, runnable.call() throws Exception and is handled, but then rethrown.

    In order to fix the compilation in this case, you must add a throws statement to your method declaration.