Learn java 8 with me(1):Lambda and exceptions
Java 8 introduced a new grammar named lamdbda expression to us, It’s very concise and simple. It’s often used with functional interfaces, which have only one abstract method.
In java8, there are many inner functional interfaces to use with lambdas, for example the Predicate<T>:
The normal way to use lambda expression: no exception to catch and throw
- Use inner functional interface to demo lambdas Predicate<T> : can be used to predict an action by paramater T It’s definition is as follows:
- Now we can define a method using the Predict<T> as the parameter:
- And then , we pass a lambda expression to the testEmpty method
- we can test it and see the output is:
But if lambda call a method with exception ,what happens?
- Firstly we define a method to test a String ,check if it is empty
- Then we call it in the lambda expression:
It wouldn’t compile!,because the isEmpty method throws a checked exception, but it’s not caught by anyone.
- Change the code to let the compiler pass
Since lambda expressions’s return is implicit, if you want to catch exception in lambda, you must use {} to encapsulate the statements.
You can find detail documents about the java8 and lambda here:
The above code examples’ source code is here: