java - 如何正确处理 catch 块内的嵌套异常
问题描述
我有以下代码,我试图了解如何正确处理 catch 块中的异常,以便抛出两个异常(mainException
和anotherException
),以防万一anotherException
我们不丢失来自mainException
. 代码也很难闻——这种try-catch用法是某种反模式吗?有没有更好/正确的方法来处理这种情况?
try {
-some code-
} catch (RuntimeException mainException) {
try {
-another code-
} catch (Exception anotherException) {
throw anotherException;
} finally {
throw mainException;
}
}
解决方案
在 Java 7 中,作为try-with-resources工作的一部分,Throwable
该类得到了扩展,支持抑制异常,特别适用于这样的场景。
public static void main(String[] args) throws Exception {
try {
throw new RuntimeException("Foo");
} catch (RuntimeException mainException) {
try {
throw new Exception("Bar");
} catch (Exception anotherException) {
mainException.addSuppressed(anotherException);
}
throw mainException;
}
}
输出(堆栈跟踪)
Exception in thread "main" java.lang.RuntimeException: Foo
at Test.main(Test.java:5)
Suppressed: java.lang.Exception: Bar
at Test.main(Test.java:8)
推荐阅读
- javascript - 如何在js的莫里斯折线图中显示日期而不是年份
- android - 带有“startForeground(..) 的服务仅在应用程序处于后台时才需要显示通知
- android - Android MediaDataSource 意外行为
- python - 如何使用 pandas 在 python 中读取 Excel 文件?
- javascript - React Native Expo AV - 音频不播放
- javascript - 如何重新加载 chrome://inspector android webview devtools
- python - read_excel() 函数自动将 int 转换为 float
- amazon-web-services - 在 Python 中使用 AWS DynamoDB CRUD 函数的问题
- c++ - 获取数组的所有连续相同数字的块
- php - Prestashop 1.7 产品列表每 30 秒刷新一次并在 ajax 调用中更新内容