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{ List<Integer> integers = Arrays.asList(3, 9, 7, 6, 10, 20, 0);
integers.forEach(i -> { try { System.out.println(50 / i); }catch (ArithmeticException ex){ ex.printStackTrace(); } });
integers.forEach(lambdaWrapper(i -> System.out.println(50 / i)));
integers.forEach(consumerWrapper(i -> System.out.println(50 / i),ArithmeticException.class));
integers.forEach(i -> { try { writeToFile(i); } catch (IOException e) { throw new RuntimeException(e); } });
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{ }
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种方式