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() 可能引发的异常.bar
的throws 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)
.
相关文章