Handle Exception Using Lambda Expression in Java



A lambda expression body can't throw any exceptions that haven't specified in a functional interface. If the lambda expression can throw an exception then the "throws" clause of a functional interface must declare the same exception or one of its subtype.

Example

interface Student {
   void studentData(String name) throws Exception;
}
public class LambdaExceptionTest {
   public static void main(String[] args) {
      // lamba expression 
      Student student = name -> {
         System.out.println("The Student name is: " + name);
         throw new Exception();
      };
      try {
         student.studentData("Adithya");
      } catch(Exception e) {

      }
   }
}

Output

The Student name is: Adithya
Updated on: 2020-07-10T12:01:45+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements