Java 8:如何在流中使用异常抛出方法? [英] Java 8: How do I work with exception throwing methods in streams?

查看:23
本文介绍了Java 8:如何在流中使用异常抛出方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类和一个方法

Suppose I have a class and a method

class A {
  void foo() throws Exception() {
    ...
  }
}

现在我想为 A 的每个实例调用 foo,这些实例由如下流传递:

Now I would like to call foo for each instance of A delivered by a stream like:

void bar() throws Exception {
  Stream<A> as = ...
  as.forEach(a -> a.foo());
}

问题:如何正确处理异常?该代码无法在我的机器上编译,因为我不处理 foo() 可能引发的异常.barthrows Exception 在这里似乎没什么用.这是为什么呢?

Question: How do I properly handle the exception? The code does not compile on my machine because I do not handle the possible exceptions that can be thrown by foo(). The throws Exception of bar seems to be useless here. Why is that?

推荐答案

你需要将你的方法调用包装到另一个中,你不会抛出检查的异常.你仍然可以抛出任何 RuntimeException 的子类.

You need to wrap your method call into another one, where you do not throw checked exceptions. You can still throw anything that is a subclass of RuntimeException.

一个普通的包装习惯是这样的:

A normal wrapping idiom is something like:

private void safeFoo(final A a) {
    try {
        a.foo();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

(超类型异常Exception作为例子,千万不要自己去捕捉)

(Supertype exception Exception is only used as example, never try to catch it yourself)

然后你可以调用它:as.forEach(this::safeFoo).

这篇关于Java 8:如何在流中使用异常抛出方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆