链接异常的优点是什么? [英] What is the advantage of chained exceptions
问题描述
我不明白代码中有链接异常的优点。
I do not understand the advantages of having a chained exception in the code.
考虑到来自java world 的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?
推荐答案
任何人都可以提供关于链接异常需求的信息? >
Can anyone please provide information on the need for chained exceptions?
文章说得很好:
异常链接允许您将一个异常类型映射到另一个异常类型,以便方法可以抛出与方法本身相同的抽象级别定义的异常,而不会丢弃重要的调试信息。
也就是说,如果你有一个从数据库加载一些对象的方法,你可能想要一些 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屋!