Reputation: 69379
Suppose I have the following code:
Runnable exceptionHandler = () -> throw new RuntimeException();
Is there a way to write it more concise, available now, or maybe available in future Java releases? I'd expect something along the lines of:
Runnable exceptionHandler = RuntimeException::throw;
For extra information, I intend to use this code for a method in which exceptional situations can occur, but not always need there be a RuntimeException
thrown. I want to give callers the freedom to do whatever they want at the point the exceptional situation occurs.
As it seems to me, this is not possible with Java 8, has this been discussed and is there any reason this is not possible?
Upvotes: 6
Views: 151
Reputation: 328785
Exception::throw
is not valid and I can't find any related discussions in the mailing lists.
However if your intent is: "to give callers the freedom to do whatever they want at the point the exceptional situation occurs", you could use a design similar to CompletableFuture
and write something like:
public static void main(String[] args) throws Exception {
CompletableFuture.runAsync(() -> somethingThatMayThrow())
.exceptionally(t -> { t.printStackTrace(); return null; });
}
private static void somethingThatMayThrow() throws RuntimeException {
throw new RuntimeException();
}
That only works with unchecked exception though.
Upvotes: 2