FP error handling – checked exceptions The code below breaks the flow of execution as the input “ABC” throws a checked exception – “NumberFormatException”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package com.fp.eg6; import java.util.stream.Stream; public class CheckedExceptionWithFPMain { public static void main(String[] args) { Stream.of("1", "ABC", "2") .map(Integer::parseInt) .forEach(System.out::println); // throws checked exception // java.lang.NumberFormatException // For "ABC" } } |
Outputs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 1 Exception in thread "main" java.lang.NumberFormatException: For input string: "ABC" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) at com.fp.eg6.CheckedExceptionWithFPMain.main(CheckedExceptionWithFPMain.java:11) |
What if you want to just mark all the inputs that throw a…