Is there a method reference to throw an exception?

Suppose I have the following code:

Runnable exceptionHandler = () -> throw new RuntimeException(); 

Is there a way to write it more concise, available now, or possibly available in future releases of Java? I would expect something like:

 Runnable exceptionHandler = RuntimeException::throw; 

For more information, I intend to use this code for a method in which exceptions may occur, but a RuntimeException not always required. I want to give subscribers the freedom to do what they want at a time when an exceptional situation arises.

It seems to me that this is not possible with Java 8, has this been discussed and is there a reason why this is not possible?

+6
source share
1 answer

Exception::throw invalid and I cannot find related discussions on the mailing lists.

However, if your intention is to “give callers the freedom to do what they want at the time of the exception,” you can 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(); } 

This only works with an unchecked exception.

+2
source

All Articles