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