3

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
Antonio Dragos
  • 1,973
  • 2
  • 29
  • 52
  • I doubt it; `throws Exception` is very broad and generally discouraged. It's better to write your own interface and specify which types of exception can be thrown. – kaya3 Nov 04 '20 at 14:55
  • @kaya3 `java.util.concurrent.Callable` declares `throws Exception` – Antonio Dragos Nov 04 '20 at 15:16
  • For Callable specifically, it is expected to run in a different thread and the exception won't be caught (it will just terminate the thread), so there is no need to specify what types of exception it might be. In that case the result is usually returned as a future, so a void return type would be unusual. Maybe [this other question](https://stackoverflow.com/questions/22795563/how-to-use-callable-with-void-return-type) is what you're looking for, though. – kaya3 Nov 04 '20 at 16:12

1 Answers1

1

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;
};
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183