我应该如何将 SQLException 包装为未经检查的异常?

发布于 2024-10-06 02:35:43 字数 213 浏览 5 评论 0原文

我们都知道SQLException是一个受检查的异常,而且我们大多数人都认为受检查的异常是冗长的并且会导致抛出/捕获污染。

我应该选择哪种方法来避免抛出 SQLException?

推荐哪种包装器/技术/库? (例如对于Spring人员来说DataAccessException,但我不想使用Spring)

We all know that SQLException is a checked Exception and most of us agree that checked exceptions are verbose and lead to throw/catch pollution.

Which approach should I choose to avoid SQLException throwing?

Which wrapper/technique/library is recommended?
(for example DataAccessException for the Spring folks, but I don't want to use Spring)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

顾冷 2024-10-13 02:35:43

只需将其包装为 new RuntimeException(jdbce) 即可。或者定义您自己的异常来扩展运行时异常并使用它。我认为这里不需要任何框架。即使 Spring 在每次需要时也会将已检查的异常包装为未检查的异常。

Just wrap it as new RuntimeException(jdbce). Or defince your own exception that extends runtime exception and use it. I do not think that any framework is required here. Even spring wraps checked exceptions by unchecked every time it needs it.

别想她 2024-10-13 02:35:43

如果您想将已检查异常视为未检查异常,您可以

在 Java 7 之前

} catch(SQLException e) {
   Thread.currentThread().stop(e);
}

执行此操作,但是在 Java 8 中您可以执行

/**
 * 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
}

并调用

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

已检查异常是一项编译器功能,在运行时不会有不同的处理方式。

If you want to treat a checked exception as an unchecked one, you can do

Up to Java 7 you can do

} catch(SQLException e) {
   Thread.currentThread().stop(e);
}

However in Java 8 you can do

/**
 * 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
}

and call

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

Checked exceptions are a compiler feature and are not treated differently at runtime.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文