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:
@FunctionalInterface
public interface Predicate<T>{
	boolean test(T t);
}
  • Now we can define a method using the Predict<T> as the parameter:
private static boolean checkString(Predicate<String> predict,
                                      String theRealString) {
    return predict.test(theRealString);
}
  • And then , we pass a lambda expression to the testEmpty method
        Predicate<String> notEmpty = (String s)->!s.isEmpty();
        System.out.println(checkString(notEmpty,"test"));
        System.out.println(checkString(notEmpty,""));
  • we can test it and see the output is:
true
false

But if lambda call a method with exception ,what happens?

  • Firstly we define a method to test a String ,check if it is empty
private static boolean isEmpty(String s) throws Exception {
    if(s==null) throw new Exception("null");
    return s.isEmpty();
}
  • Then we call it in the lambda expression:
Predicate<String> notEmpty = (String s)->!isEmpty(s);//compile error

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
	Predicate<String> notEmpty = (String s) -> {
        try {
            return !isEmpty(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    };

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: