Java 8 lambda表达式中的异常处理

20 篇文章 0 订阅

1 概述

在Java 8 中,当写lambda表达式并处理异常时代码变得冗余不堪,本文主要介绍lambda表达式中一些异常处理方式。

2 处理 Unchecked 异常(不处理编译通过)

下面的代码,当i为0时会引发ArithmeticException异常。

List<Integer> integers = Arrays.asList(3, 9, 7, 6, 10, 20);
integers.forEach(i -> System.out.println(50 / i));

通常的做法是通过try…catch来处理异常,防止系统崩溃。

List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
integers.forEach(i -> {
    try {
        System.out.println(50 / i);
    } catch (ArithmeticException e) {
        System.err.println(
          "Arithmetic Exception occured : " + e.getMessage());
    }
});

使用try…catch后代码不再像以前一样简洁。我们可以通过写一个包装方法来进行处理。

static Consumer<Integer> lambdaWrapper(Consumer<Integer> consumer) {
    return i -> {
        try {
            consumer.accept(i);
        } catch (ArithmeticException e) {
            System.err.println(
              "Arithmetic Exception occured : " + e.getMessage());
        }
    };
}
List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
integers.forEach(lambdaWrapper(i -> System.out.println(50 / i)));

通过编写包装方法lambdaWrapper并接收一个lambda表达式,在该方法内会进行异常处理。因此对于同类问题就可以避免反复写try…catch。

再次改进增加一个异常类型, 可以抛出我们希望抛出的异常。

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.err.println(
                  "Exception occured : " + exCast.getMessage());
            } catch (ClassCastException ccEx) {
                throw ex;
            }
        }
    };
}
List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
integers.forEach(
  consumerWrapper(
    i -> System.out.println(50 / i), 
    ArithmeticException.class));

类似的可以根据实际需求写出各种类型的函数式接口包装类,如Function, BiFunction, BiConsumer等。

3 处理 Checked 异常(不处理编译不通过)

这个例子中writeToFile会抛出IOException。IOException是一个Checked异常,所以必须处理。因此要么抛出要么捕获。

static void writeToFile(Integer integer) throws IOException {
    // logic to write to file which throws IOException
}
List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
integers.forEach(i -> writeToFile(i));

3.1 从Lambda表达式中抛出Checked异常

throws抛出异常仍然会提示错误unhandled IOException。

public static void main(String[] args) throws IOException {
    List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
    integers.forEach(i -> writeToFile(i));
}

尝试实现Consumer,并指定accept抛出Exception,仍然错误。因为accept定义中并未
抛出任何异常。

Consumer<Integer> consumer = new Consumer<Integer>() {
  
    @Override
    public void accept(Integer integer) throws Exception {
        writeToFile(integer);
    }
};

最直接的处理方法是通过try…catch捕获。

List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
integers.forEach(i -> {
    try {
        writeToFile(i);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
});

其次我们可以通过自定义函数式接口并声明方法抛出异常。

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

编写包装类,接着使用,这样在foreach中方法不但可以抛出异常同时又能保持简洁性。

static <T> Consumer<T> throwingConsumerWrapper(
  ThrowingConsumer<T, Exception> throwingConsumer) {
  
    return i -> {
        try {
            throwingConsumer.accept(i);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    };
}
List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
integers.forEach(throwingConsumerWrapper(i -> writeToFile(i)));

3.2 在Lambda表达式中处理Checked异常

接着对throwingConsumerWrapper进行改造,使其能接收一个异常类型参数。

static <T, E extends Exception> Consumer<T> handlingConsumerWrapper(
  ThrowingConsumer<T, E> throwingConsumer, Class<E> exceptionClass) {
  
    return i -> {
        try {
            throwingConsumer.accept(i);
        } catch (Exception ex) {
            try {
                E exCast = exceptionClass.cast(ex);
                System.err.println(
                  "Exception occured : " + exCast.getMessage());
            } catch (ClassCastException ccEx) {
                throw new RuntimeException(ex);
            }
        }
    };
}
List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
integers.forEach(handlingConsumerWrapper(
  i -> writeToFile(i), IOException.class));

类似的,可以根据实际需求编写ThowingFunction, ThrowingBiFunction, ThrowingBiConsumer。

4 结束语

本文主要介绍了java 8Lamda表达式的异常处理方式,如果希望使用现成的工具可以考虑Vavr或ThrowingFunction,这两个工具值得一看。vavr的功能简介可参考https://blog.csdn.net/revivedsun/article/details/80088080。

5 原文地址

https://blog.csdn.net/Revivedsun/article/details/79906165

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值