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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:10:59  来源:igfitidea点击:

DataAccessException vs SQLException

javaspringexception

提问by Nital

I have two questions related to exception handling in Spring framework.

我有两个与 Spring 框架中的异常处理相关的问题。

  1. Why is Spring framework's DataAccessExceptiona runtime exception whereas core Java's SQLExceptiona checked exception?

  2. What advantage does Spring's exception handling offers over Java's exception handling mechanism?

  1. 为什么 Spring 框架DataAccessException是运行时异常,而核心 Java 是SQLException已检查异常?

  2. Spring 的异常处理相比 Java 的异常处理机制有什么优势?

采纳答案by Todd

The reason to use DataAccessExceptionover SQLExceptionis 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.

使用DataAccessExceptionover的原因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 SQLExceptionor DataAccessExceptionis 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.

至于为什么这是运行时而不是检查异常,它允许调用者不必显式处理它。根据我的经验,如果一个SQLExceptionorDataAccessException被抛出,除了让它冒泡给可以的人之外,我无能为力或不想做太多事情。必须在每一层声明 throwable 对调用者来说负担更大。如果他们中的一个人想抓住并处理它,他们可以。

Here are the JavaDocs (thanks @Tom!)

这是 JavaDocs(感谢 @Tom!)

  1. DataAccesssException
  2. SQLException
  1. 数据访问异常
  2. SQL异常