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?
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.
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.
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 ...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With