Java 8:如何使用流中的异常抛出方法? [英] Java 8: How do I work with exception throwing methods in streams?
问题描述
假设我有一个类和一个方法
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
的异常
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);
}
}
(超类型异常例外
仅以 为例,从不尝试自己捕获它。
(Supertype exception Exception
is only used as example, never try to catch it yourself)
然后你可以用: as.forEach(this :: safeFoo)
。
这篇关于Java 8:如何使用流中的异常抛出方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!