In this post we'll see how to do excpetion handling in Java Lambda expression.
Rules for Lambda expression exception handling
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
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.
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
You may also like-
Hello,
ReplyDeleteThis is good article , it will be better if you will put here complete example.