Handling Exceptions in Lambda Example
This program demonstrates handling exceptions in lambda expressions.
Problem Statement
Write a Java program that handles exceptions inside lambda expressions.
Source Code
| 1 | import java.util.*; |
| 2 | public class LambdaExceptionExample { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Lambda Exception Example"); |
| 5 | List<String> list=Arrays.asList("10","abc","20"); |
| 6 | list.forEach(s -> { |
| 7 | try { |
| 8 | int num=Integer.parseInt(s); |
| 9 | System.out.println("Eduinq Number: "+num); |
| 10 | } catch(NumberFormatException e) { |
| 11 | System.out.println("Eduinq Exception: Invalid Input - "+s); |
| 12 | } |
| 13 | }); |
| 14 | } |
| 15 | } |
Program Output
Eduinq Lambda Exception Example Eduinq Number: 10 Eduinq Exception: Invalid Input - abc Eduinq Number: 20
Explanation
Lambda expressions can include try-catch for exception handling. - Prevents termination of stream or iteration. - Improves robustness in functional programming. - In enterprise systems, lambda exception handling ensures safe data processing. Conclusion: Shows handling exceptions in lambda expressions.