我不明白在代码中使用链式异常有什么好处。
考虑到 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/