Java DataAccessException 与 SQLException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27869710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataAccessException vs SQLException
提问by Nital
I have two questions related to exception handling in Spring framework.
我有两个与 Spring 框架中的异常处理相关的问题。
Why is Spring framework's
DataAccessException
a runtime exception whereas core Java'sSQLException
a checked exception?What advantage does Spring's exception handling offers over Java's exception handling mechanism?
为什么 Spring 框架
DataAccessException
是运行时异常,而核心 Java 是SQLException
已检查异常?Spring 的异常处理相比 Java 的异常处理机制有什么优势?
采纳答案by Todd
The reason to use DataAccessException
over SQLException
is that it more generally describes the problem. If you have a Repository or DAO interface that has two different implementations, one for Oracle and one for Cassandra, you can have this one exception express failures for both implementations.
使用DataAccessException
over的原因SQLException
是它更一般地描述了问题。如果您的 Repository 或 DAO 接口具有两种不同的实现,一种用于 Oracle,另一种用于 Cassandra,则您可以将这两种实现的异常表示失败。
As for why this is Runtime and not a checked exception, it allows the callers to not have to explicitly handle it. It seems in my experience that if an SQLException
or DataAccessException
is thrown there's not much I can or want to do about it other than let it bubble up to somebody that can. Having to declare the throwables at each layer is more burden on the caller. If one of them cares to catch and handle it, they can.
至于为什么这是运行时而不是检查异常,它允许调用者不必显式处理它。根据我的经验,如果一个SQLException
orDataAccessException
被抛出,除了让它冒泡给可以的人之外,我无能为力或不想做太多事情。必须在每一层声明 throwable 对调用者来说负担更大。如果他们中的一个人想抓住并处理它,他们可以。
Here are the JavaDocs (thanks @Tom!)
这是 JavaDocs(感谢 @Tom!)