java - 链式异常的优点是什么

标签 java exception-handling

我不明白在代码中使用链式异常有什么好处。

考虑到 ResourceLoader example from java world ,如果程序员知道遇到 ResourceLoadException 的可能性,为什么不捕获相同的异常而不是 SQLException?否则,程序员可以在同一代码中捕获这两个异常,而不必抛出一个新的 Throwable 实例?

最佳答案

Can anyone please provide information on the need for chained exceptions?

文章说的很好:

Exception chaining allows you to map one exception type to another, so that a method can throw exceptions defined at the same abstraction level as the method itself, without discarding important debugging information.

也就是说,如果您有一个从数据库加载某些对象的方法,您可能更需要一些 ResourceLoadException(与方法抽象级别更相关)而不是低级 SQLException 即使那是问题的原始根源。但是,如果您只是捕获 SQLException 并抛出 ResourceLoadException,您可能会丢失重要的调试信息。

因此,链接异常是一个很好的选择。您抛出一个“高级”异常,非常适合特定方法,但将其与导致它的异常链接起来。

Else, the programmer can catch both the exceptions in the same code than having to throw a new Throwable instance?

我不太理解你的推理。关键是他不需要担心这个抽象级别的 SQLException

关于java - 链式异常的优点是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5020876/

相关文章:

oracle - PL/SQL异常处理

language-agnostic - 有人可以向我解释异常处理吗?

java - 从字节 [] 而非文件加载图像 OpenCV (JavaCV)

java - Spring Boot REST 服务异常处理

java - Optional in orElse-Branch throws Exception

java - 如何在 Spring Data JPA 中使用 CTE 表达式 WITH 子句

spring-mvc - 在 Spring Security 中传播 AccessDeniedException

java - 如何从 Java 设置环境变量?

java - 根据主体tomcat重定向请求

java - 没有异或的按位交换