技术编程5万字:Stream和Lambda表达式最佳实践2


7.2 处理checked Exception
checked Exception是必须要处理的异常 , 我们还是看个例子:static void throwIOException(Integer integer) throws IOException {}复制代码List
integers = Arrays.asList(1, 2, 3, 4, 5);integers.forEach(i -> throwIOException(i));复制代码
上面我们定义了一个方法抛出IOException , 这是一个checked Exception , 需要被处理 , 所以在下面的forEach中 , 程序会编译失败 , 因为没有处理相应的异常 。
最简单的办法就是try , catch住 , 如下所示:integers.forEach(i -> {try {throwIOException(i);} catch (IOException e) {throw new RuntimeException(e);}});复制代码
当然 , 这样的做法的坏处我们在上面已经讲过了 , 同样的 , 我们可以定义一个新的wrapper方法:staticConsumer consumerWrapper(ThrowingConsumer
throwingConsumer) {return i -> {try {throwingConsumer.accept(i);} catch (Exception ex) {throw new RuntimeException(ex);}};}复制代码
我们这样调用:integers.forEach(consumerWrapper(i -> throwIOException(i)));复制代码
我们也可以封装一下异常:static
Consumer consumerWrapperWithExceptionClass(ThrowingConsumer
throwingConsumer, Class
{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);}}};}复制代码
然后这样调用:integers.forEach(consumerWrapperWithExceptionClass(i -> throwIOException(i), IOException.class));复制代码8. stream中throw Exception
之前的文章我们讲到 , 在stream中处理异常 , 需要将checked exception转换为unchecked exception来处理 。
我们是这样做的:staticConsumer consumerWrapper(ThrowingConsumer
throwingConsumer) {return i -> {try {throwingConsumer.accept(i);} catch (Exception ex) {throw new RuntimeException(ex);}};}复制代码
将异常捕获 , 然后封装成为RuntimeException 。
封装成RuntimeException感觉总是有那么一点点问题 , 那么有没有什么更好的办法?8.1 throw小诀窍
java的类型推断大家应该都知道 , 如果是 这样的形式 , 那么T将会被认为是RuntimeException!
我们看下例子:public class RethrowException {public static
R throwException(Exception t) throws T {throw (T) t; // just throw it, convert checked exception to unchecked exception}}复制代码
上面的类中 , 我们定义了一个throwException方法 , 接收一个Exception参数 , 将其转换为T , 这里的T就是unchecked exception 。
接下来看下具体的使用:@Slf4jpublic class RethrowUsage {public static void main(String[] args) {try {throwIOException();} catch (IOException e) {log.error(e.getMessage(),e);RethrowException.throwException(e);}}static void throwIOException() throws IOException{throw new IOException("io exception");}}复制代码
上面的例子中 , 我们将一个IOException转换成了一个unchecked exception 。 9. stream中Collectors的用法
在java stream中 , 我们通常需要将处理后的stream转换成集合类 , 这个时候就需要用到stream.collect方法 。 collect方法需要传入一个Collector类型 , 要实现Collector还是很麻烦的 , 需要实现好几个接口 。
于是java提供了更简单的Collectors工具类来方便我们构建Collector 。


推荐阅读