Is there a JDK functional interface that takes no arguments, returns nothing and allows checked exceptions?

Viewed 109

I'm looking in the JDK for a functional interface with a method signature like this

@FunctionalInterface
public interface Executable {

    void execute() throws Exception;
}

But surprisingly, I can't seem to find one.

1 Answers

The only functional interface I am aware of in Java that allows to throw a checked exception is java.util.concurrent.Callable. Here is it's source code:

@FunctionalInterface
public interface Callable<V> {

    V call() throws Exception;
}

It is qualified in the way it accepts nothing, however, it has a return type. You can use a trick with Void to specify that nothing should be expected:

void method() throws Exception {
    throw new Exception("I am so dumb I always throw the exception");
}
Callable<Void> callable = () -> {
    method();
    return null;
};
Related