Lambda异常处理方案(未完成)

Lambda异常处理方案

第一节 概述

JDK虽然提供了Lambda表达式,但这些功能接口不能很好地处理异常,使代码变得繁琐和冗长,从而失去了Lambda表达式的优势。

第二节 Unchecked和Checked异常处理

如下代码案例,分别处理未检异常和受检异常。

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
75
76
77
78
79
80
81
82
83
84
85
86
public class Test {
public static void main(String[] args) throws IOException{
//案例:当i为0时会引发异常ArithmeticException: / by zero,是一个Unchecked异常
List<Integer> integers = Arrays.asList(3, 9, 7, 6, 10, 20, 0);

// integers.forEach(i -> System.out.println(50 / i));

//通常使用try-catch来处理,但这种方式不够简洁,也不够灵活
integers.forEach(i -> {
try {
System.out.println(50 / i);
}catch (ArithmeticException ex){
ex.printStackTrace();
}
});

//我们通过引入一个包装方法来让其简洁化,把异常处理放到方法内处理,避免重复的写try-catch
integers.forEach(lambdaWrapper(i -> System.out.println(50 / i)));

//再改进包装方法使其可以适用更多的异常
integers.forEach(consumerWrapper(i -> System.out.println(50 / i),ArithmeticException.class));

//新案例会抛出IOException,是一个Checked异常,如下会提示异常未处理,即使在当前调用函数中抛出异常
// integers.forEach(i -> writeToFile(i));

//最直接的方案仍是try-catch来处理
integers.forEach(i -> {
try {
writeToFile(i);
} catch (IOException e) {
throw new RuntimeException(e);
}
});

//通过声明接口ThrowingConsumer使代码可以抛出异常,
integers.forEach(throwingConsumerWrapper(i -> writeToFile(i),IOException.class));
}

static Consumer<Integer> lambdaWrapper(Consumer<Integer> consumer){
return i -> {
try {
consumer.accept(i);
}catch (ArithmeticException ex){
ex.printStackTrace();
}
};
}

static <T, E extends Exception> Consumer<T> consumerWrapper(Consumer<T> consumer, Class<E> clazz){
return i -> {
try {
consumer.accept(i);
}catch (Exception ex){
try {
E exCast = clazz.cast(ex);
System.out.println(exCast.toString());
ex.printStackTrace();
} catch (ClassCastException ccEx) {
throw ex;
}
}
};
}

static void writeToFile(Integer integer) throws IOException{
//省略
}

//通过包装类将产生的Exception转为RuntimeException
static <T, E extends Exception> Consumer<T> throwingConsumerWrapper(
ThrowingConsumer<T, E> throwingConsumer, Class<E> exceptionClass){
return i -> {
try {
throwingConsumer.accept(i);
}catch (Exception ex){
try {
E exCast = exceptionClass.cast(ex);
System.out.println(exCast.toString());
ex.printStackTrace();
} catch (ClassCastException ccEx) {
throw new RuntimeException(ex);
}
}
};
}
}

函数式接口ThrowingConsumer用来声明可抛出异常的Consumer。

1
2
3
4
@FunctionalInterface
public interface ThrowingConsumer<T, E extends Exception> {
void accept(T t) throws E;
}

函数式接口ThrowingFunction用来声明可抛出异常的Function。

1
2
3
4
5
6
7
8
9
10
11
12
@FunctionalInterface
public interface ThrowingFunction<T, R, E extends Exception> extends Function<T, R> {
default R apply(T t){
try {
return applyThrows(t);
}catch (Exception ex){
System.out.println("handling an exception...");
throw new RuntimeException(ex);
}
}
R applyThrows(T t) throws E;
}

等等。


参考:

🔗 Exceptions in Java 8 Lambda Expressions

🔗 Java 8 Stream 中异常处理的4种方式