Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a Java Lambda which throws a Runtime Exception require brackets?

I understand that a lambda in java cannot throw a checked exception, but can throw a RuntimeException, but why does the below code require brackets?

Map<String, Integer> m = new HashMap<>();
Integer integer = m.computeIfAbsent("", s -> {throw new IllegalArgumentException("fail");});

Why can't you have?

m.computeIfAbsent("", s -> throw new IllegalArgumentException("fail"));

Is it due to the assumption of the compiler that it would return in this instance an int, so therefor can't have a return of an exception, even though its thrown?

like image 444
Ash Avatar asked Jan 31 '17 15:01

Ash


People also ask

What happens when AWS Lambda throws exception?

If Lambda encounters an error, it returns an exception type, message, and HTTP status code that indicates the cause of the error. The client or service that invoked the Lambda function can handle the error programmatically, or pass it along to an end user.

How does lambdas handle exceptions in Java?

The most straightforward way would be to use a try-catch block, wrap the checked exception into an unchecked exception and rethrow it: List<Integer> integers = Arrays. asList(3, 9, 7, 0, 10, 20); integers. forEach(i -> { try { writeToFile(i); } catch (IOException e) { throw new RuntimeException(e); } });

Can we throw exception from lambda expression in Java?

A lambda expression body can't throw any exceptions that haven't specified in a functional interface. If the lambda expression can throw an exception then the "throws" clause of a functional interface must declare the same exception or one of its subtype.

How is lambda represented at runtime?

For Lambda expressions, the compiler doesn't translate them into something which is already understood by JVM. Lambda syntax that is written by the developer is desugared into JVM level instructions generated during compilation, which means the actual responsibility of constructing lambda is deferred to runtime.


1 Answers

The Java Language Specification describes the body of a lambda expression

A lambda body is either a single expression or a block (§14.2).

This, however,

throw new IllegalArgumentException("fail")

is the throw statement, not an expression. The compiler therefore rejects it as the lambda expression's body.

You can go down the rabbit hole and learn what all the types of expressions are, here (follow the grammar).

like image 103
Sotirios Delimanolis Avatar answered Sep 23 '22 15:09

Sotirios Delimanolis