Java 8: How do I work with exception throwing methods in streams?(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)
.
这篇关于Java 8:如何在流中使用异常抛出方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8:如何在流中使用异常抛出方法?


- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01