Wednesday, 3 June 2015

Lambda expression and exception handling

A lambda expression can throw an exception but lambda expression must throw exception compatible with those specified in the throws clause of the functional interface method.

If a lambda expression body throws an exception, the throws clause of the functional interface method must declare the same exception type or its supertype or in other words the exception thrown from the lambda expression must be same or subtype of the exception declared in the throws clause of the functional interface.

If a functional interface doesn't specify any exception with a throws clause then lambda expression also can't throw any exception. Let's see it with an example.

Lambda expression excpetion handling1

It can be seen here that in the abstract method of the functional interface there is no throws clause but we are trying to give one with lambda expression causing the compile time error.

Example with proper exception

interface IFuncInt {
    int func(int num1, int num2) throws Exception;
}

public class LambdaExceptionDemo {
    public static void main(String[] args){
        IFuncInt funcInt = (num1, num2) -> {
            int result = num1 +  num2;
            throw new Exception();
            
        };
        try {
            System.out.println("" + funcInt.func(6, 7));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

It can be seen that there won't be any compiler error if throws clause is declared in the functional interface method. But make sure to enclose the call to method (funcInt.func(6, 7) in this case) with in try-catch block or declare exception with throws in the main method.

Also if we try to throw the supertype exception from the lambda expression then it will give error.

Example

lambda expression exception handling2

Here in the functional interface method in the throws clause FileNotFoundException is declared but in lambda expression IOException is thrown, which is the super class of FileNotFoundExpcetion. Thus the compiler error.

That's all for this topic Lambda expression and exception handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Overview of lambda expressions
  2. Functional interfaces & lambda expression
  3. Lambda expression as method parameter
  4. Lambda expression and variable scope
  5. Functional interface annotation in Java 8
  6. Lambda expression examples in Java 8
  7. Method reference in Java 8
  8. Overview of Exception handling in Java

You may also like -

No comments:

Post a Comment