Tuesday, April 16, 2019

Exception Handling in Java Lambda Expressions

A lambda expression in Java can throw an exception but that exception must be 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 in Java.

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.

Throwing checked exception from lambda expression

Java Lambda expression exception handling

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.

Lambda expression exception handling example

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 Exception Handling in Java Lambda Expressions. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Lambda Expressions in Java 8
  2. Lambda Expression as Method Parameter
  3. Lambda Expression Examples in Java 8
  4. Overview of Exception handling in Java
  5. Java Lambda Expressions Interview Questions

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. How ArrayList works internally in Java
  3. try-with-resources in Java 7
  4. interface static methods in Java 8
  5. Synchronization in Java multithreading
  6. Inter-thread communication using wait, notify and notifyAll
  7. Callable and Future in Java concurrency
  8. How to Create PDF From XML Using Apache FOP