DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

Error Handling In Java Stream

原文链接

1
2
3
4
5
6
7
8
9
10
11
12
static Consumer<String> exceptionHandledConsumer(Consumer<String> unhandledConsumer) {
return obj -> {
try {
unhandledConsumer.accept(obj);
} catch (NumberFormatException e) {
System.err.println(
"Can't format this string");
}
};
}public static void main(String[] args) {
List<String> integers = Arrays.asList("44", "xyz", "145"); integers.forEach(exceptionHandledConsumer(str -> System.out.println(Integer.parseInt(str))));
}

采用流式的处理方式,尽可能generics

进一步:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
static <Target, ExObj extends Exception> Consumer<Target> handledConsumer(Consumer<Target> targetConsumer, Class<ExObj> exceptionClazz) {    return obj -> {
try {
targetConsumer.accept(obj);
} catch (Exception ex) {
try {
ExObj exCast = exceptionClazz.cast(ex);
System.err.println(
"Exception occured : " + exCast.getMessage());
} catch (ClassCastException ccEx) {
throw ex;
}
}
};
}


List<String> integers = Arrays.asList("44", "373", "xyz", "145");integers.forEach(
handledConsumer(str -> System.out.println(Integer.parseInt(str)),
NumberFormatException.class));

采用FunctionalInterface的方式,进一步提升,将函数提升到类?

1
2
3
4
5
6
7
8
9
10
11
12
@FunctionalInterface
public interface HandlingConsumer<Target, ExObj extends Exception> {
void accept(Target target) throws ExObj; static <Target> Consumer<Target> handlingConsumerBuilder(
HandlingConsumer<Target, Exception> handlingConsumer) { return obj -> {
try {
handlingConsumer.accept(obj);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
}
}

要经常性使用stream的方式,利用函数式的思路

多用lambda表达式