Handling Exceptions in Streams Example
This program demonstrates handling exceptions in Java streams.
Problem Statement
Write a Java program that handles exceptions during stream operations.
Source Code
| 1 | import java.util.*; |
| 2 | public class StreamsExceptionExample { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Streams Exception Example"); |
| 5 | List<String> list=Arrays.asList("10","abc","20"); |
| 6 | list.stream().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 Number - "+s); |
| 12 | } |
| 13 | }); |
| 14 | } |
| 15 | } |
Program Output
Eduinq Streams Exception Example Eduinq Number: 10 Eduinq Exception: Invalid Number - abc Eduinq Number: 20
Explanation
Streams may encounter exceptions during operations like parsing. - Handling exceptions inside lambda ensures smooth processing. - Prevents stream termination due to single error. - In enterprise systems, stream exception handling ensures robust data pipelines. Conclusion: Shows handling exceptions in streams.