链式异常有什么好处 [英] What is the advantage of chained exceptions

查看:25
本文介绍了链式异常有什么好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白在代码中使用链式异常的好处.

I do not understand the advantages of having a chained exception in the code.

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

Considering the ResourceLoader example from java world, if the programmer knows of a possibility of encountering ResourceLoadException , why not catch the same exception instead of SQLException? Else, the programmer can catch both the exceptions in the same code than having to throw a new Throwable instance?

推荐答案

谁能提供有关链式异常需求的信息?

这篇文章说得很好:

异常链允许您将一种异常类型映射到另一种异常类型,以便方法可以抛出定义在与方法本身相同的抽象级别的异常,而不会丢弃重要的调试信息.

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

That is, if you have a method that loads some object from a database, you may rather want some ResourceLoadException (closer related to the methods abstraction level) instead of a low-level SQLException even if that was the original source of the problem. However, if you simply catch the SQLException and throw a ResourceLoadException instead, you may loose important debugging information.

因此,链接异常是一个不错的选择.您抛出一个高级"异常,非常适合特定方法,但将其与导致它的异常链接起来.

Thus, chaining the exceptions is a good alternative. You throw a "high-level" exception, well suited for the particular method, but chain it with the exception that caused it.

否则,与必须抛出一个新的 Throwable 实例相比,程序员可以在同一代码中捕获这两个异常吗?

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

I don't quite follow your reasoning here. The point is that he should not need to worry about the SQLException at this level of abstraction.

这篇关于链式异常有什么好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆