What are the rules to follow while using exceptions in java lambda expressions?

Java 8Object Oriented ProgrammingProgramming

The lambda expressions can't be executed on their own. It is used to implement methods that have declared in a functional interface. We need to follow a few rules in order to use the exception handling mechanism in a lambda expression.

Rules for Lambda Expression

  • A lambda expression cannot throw any checked exception until its corresponding functional interface declares a throws clause.
  • An exception thrown by any lambda expression can be of the same type or sub-type of the exception declared in the throws clause of its functional interface.

Example-1

interface ThrowException {
   void throwing(String message);
}
public class LambdaExceptionTest1 {
   public static void main(String[] args) {
      ThrowException te = msg -> {     // lambda expression
         throw new RuntimeException(msg); // RuntimeException is not a checked exception
      };
      te.throwing("Lambda Expression");
   }
}

Output

Exception in thread "main" java.lang.RuntimeException: Lambda Expression
   at LambdaExceptionTest1.lambda$main$0(LambdaExceptionTest1.java:8)
   at LambdaExceptionTest1.main(LambdaExceptionTest1.java:10)


Example-2

import java.io.*;

interface ThrowException {
   void throwing(String message) throws IOException;
}
public class LambdaExceptionTest2 {
   public static void main(String[] args) throws Exception {
      ThrowException te = msg -> {    // lambda expression
         throw new FileNotFoundException(msg); // FileNotFoundException is a sub-type of IOException
      };
      te.throwing("Lambda Expression");
   }
}

Output

Exception in thread "main" java.io.FileNotFoundException: Lambda Expression
   at LambdaExceptionTest2.lambda$main$0(LambdaExceptionTest2.java:9)
   at LambdaExceptionTest2.main(LambdaExceptionTest2.java:11)
raja
Published on 20-Dec-2019 13:06:16
Advertisements