|
| 1 | +package com.javatechie.exception_handling; |
| 2 | + |
| 3 | +import java.lang.annotation.Target; |
| 4 | +import java.util.*; |
| 5 | +import java.util.function.Consumer; |
| 6 | +import java.util.stream.Collectors; |
| 7 | + |
| 8 | +public class ExceptionHandlingExample { |
| 9 | + |
| 10 | + public static void main(String[] args) { |
| 11 | + |
| 12 | + List<String> list = Arrays.asList("44", "373", "xyz"); |
| 13 | + List<Integer> list1 = Arrays.asList(1,0); |
| 14 | + // list1.forEach(handleGenericException(s-> System.out.println(10/s),ArithmeticException.class)); |
| 15 | + |
| 16 | + // list.forEach(handleGenericException(s -> System.out.println(Integer.parseInt(s)),NumberFormatException.class)); |
| 17 | + |
| 18 | + // List<Integer> intList = list.stream().map(Integer::parseInt).collect(Collectors.toList()); |
| 19 | + // System.out.println(intList); |
| 20 | + |
| 21 | + //handle exception for checkedException |
| 22 | + List<Integer> list2 = Arrays.asList(10,20); |
| 23 | + |
| 24 | + list2.forEach(handleCheckedExceptionConsumer(i->{ |
| 25 | + Thread.sleep(i); |
| 26 | + System.out.println(i); |
| 27 | + })); |
| 28 | + } |
| 29 | + //approach -2 |
| 30 | + |
| 31 | + public static void printList(String s) { |
| 32 | + try { |
| 33 | + System.out.println(Integer.parseInt(s)); |
| 34 | + } catch (Exception ex) { |
| 35 | + System.out.println("exception : " + ex.getMessage()); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + static Consumer<String> handleExceptionIfAny(Consumer<String> payload) { |
| 40 | + return obj -> { |
| 41 | + try { |
| 42 | + payload.accept(obj); |
| 43 | + } catch (Exception ex) { |
| 44 | + System.out.println("exception : " + ex.getMessage()); |
| 45 | + } |
| 46 | + }; |
| 47 | + } |
| 48 | + |
| 49 | + static <Target, ExObj extends Exception> Consumer<Target> handleGenericException(Consumer<Target> targetConsumer, |
| 50 | + Class<ExObj> exObjClass) { |
| 51 | + return obj -> { |
| 52 | + try { |
| 53 | + targetConsumer.accept(obj); |
| 54 | + } catch (Exception ex) { |
| 55 | + try { |
| 56 | + ExObj exObj = exObjClass.cast(ex); |
| 57 | + System.out.println("exception : " + exObj.getMessage()); |
| 58 | + } catch (ClassCastException ecx) { |
| 59 | + throw ex; |
| 60 | + } |
| 61 | + } |
| 62 | + }; |
| 63 | + } |
| 64 | + |
| 65 | + static <Target> Consumer<Target> handleCheckedExceptionConsumer(CheckedExceptionHandlerConsumer<Target,Exception> handlerConsumer){ |
| 66 | + return obj -> { |
| 67 | + try { |
| 68 | + handlerConsumer.accept(obj); |
| 69 | + } catch (Exception ex) { |
| 70 | + throw new RuntimeException(ex); |
| 71 | + } |
| 72 | + }; |
| 73 | + } |
| 74 | +} |
0 commit comments