如何包装已检查的异常但在Java中保留原始运行时异常 [英] How to wrap checked exceptions but keep the original runtime exceptions in Java

查看:417
本文介绍了如何包装已检查的异常但在Java中保留原始运行时异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可能会抛出已检查和运行时异常。

I have some code that might throw both checked and runtime exceptions.

我想捕获已检查的异常并将其包装为运行时异常。但是如果抛出RuntimeException,我不必将它包装起来,因为它已经是运行时异常。

I'd like to catch the checked exception and wrap it with a runtime exception. But if a RuntimeException is thrown, I don't have to wrap it as it's already a runtime exception.

我所拥有的解决方案有点开销而不是整洁:

The solution I have has a bit overhead and isn't "neat":

try {
  // some code that can throw both checked and runtime exception
} catch (RuntimeException e) {
  throw e;
} catch (Exception e) {
  throw new RuntimeException(e);
}

想要更优雅的方式吗?

推荐答案

我使用盲重新抛出来传递已检查的异常。我已经使用它来传递Streams API,我不能使用抛出已检查异常的lambdas。例如,我们有ThrowingXxxxx功能接​​口,因此可以传递已检查的异常。

I use a "blind" rethrow to pass up checked exceptions. I have used this for passing through the Streams API where I can't use lambdas which throw checked exceptions. e.g We have ThrowingXxxxx functional interfaces so the checked exception can be passed through.

这允许我自然地在调用者中捕获已检查的异常,而无需知道被调用者必须通过一个不允许检查异常的接口传递它。

This allows me to catch the checked exception in a caller naturally without needing to know a callee had to pass it through an interface which didn't allow checked exceptions.

try {
  // some code that can throw both checked and runtime exception

} catch (Exception e) {
  throw rethrow(e);
}

在调用方法中,我可以再次声明已检查的异常。

In a calling method I can declare the checked exception again.

public void loadFile(String file) throws IOException {
   // call method with rethrow
}







/**
 * Cast a CheckedException as an unchecked one.
 *
 * @param throwable to cast
 * @param <T>       the type of the Throwable
 * @return this method will never return a Throwable instance, it will just throw it.
 * @throws T the throwable as an unchecked throwable
 */
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
    throw (T) throwable; // rely on vacuous cast
}

处理异常有很多不同的选项。我们使用其中的一些。

There is a lot of different options for handling exceptions. We use a few of them.

https://vanilla-java.github.io/2016/06/21/Reviewing-Exception-Handling.html

这篇关于如何包装已检查的异常但在Java中保留原始运行时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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