Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method reference available for throwing 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 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?

like image 490
skiwi Avatar asked Apr 09 '14 10:04

skiwi


People also ask

Which methods can throw an exception?

All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.

Does a method have to throw an exception?

Therefore, any code that calls a method that declares that it throws Exception must handle or declare it. Every method in the chain is declared to throw Exception, including main.

How do you know if a method throws an exception?

The calculate method should check for an exception and if there is no exception, return the calculated value to the main function i.e. v1+v2 or v1-v2; Else if an exception exists then it should print the error statement and the value that is returned from the calculate method to the main method should be 0.0(Not ...

How do you call a method that throws an exception in Java?

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.


1 Answers

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.

like image 175
assylias Avatar answered Oct 02 '22 16:10

assylias