我应该如何将 SQLException 包装为未经检查的异常?
我们都知道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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将其包装为
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.如果您想将已检查异常视为未检查异常,您可以
在 Java 7 之前
执行此操作,但是在 Java 8 中您可以执行
并调用
已检查异常是一项编译器功能,在运行时不会有不同的处理方式。
If you want to treat a checked exception as an unchecked one, you can do
Up to Java 7 you can do
However in Java 8 you can do
and call
Checked exceptions are a compiler feature and are not treated differently at runtime.