问题描述
异常翻译
和异常链接
在Java中有什么区别?
What is the difference between Exception Translation
and Exception Chaining
in Java?
推荐答案
根据有效Java 中的 Joshua Bloch -
异常翻译
较高的层应捕获较低级别的异常
,并代之以可以用$ b解释的异常$ b较高级别的抽象。
Exception Translation
Higher layers should catch lower-level exceptionsand, in their place, throw exceptions that can be explained in terms of thehigher-level abstraction.
try {
// Use lower-level abstraction to do our bidding
...
} catch(LowerLevelException e) {
throw new HigherLevelException(...);
}
异常链接
它是异常翻译的一种特殊形式。
如果较低级别的异常可能有助于调试
的人,则该问题会导致较高级别的异常。较低级别的异常(原因)被传递给较高级别的异常,该异常提供了
访问器方法(Throwable.getCause)来检索较低级别的异常:
Exception Chaining
It is special form of exception translation.In cases where the lower-level exception might be helpful to someone debuggingthe problem that caused the higher-level exception. The lower-level exception (the cause) is passed to the higher-level exception, which provides anaccessor method (Throwable.getCause) to retrieve the lower-level exception:
try {
... // Use lower-level abstraction to do our bidding
} catch (LowerLevelException cause) {
throw new HigherLevelException(cause);
}
高级异常的构造方法将原因传递给可链接的
超类构造函数,因此最终将其传递给Throwable的chainingaware构造函数之一,例如Throwable(Throwable):
The higher-level exception’s constructor passes the cause to a chaining-awaresuperclass constructor, so it is ultimately passed to one of Throwable’s chainingaware constructors, such as Throwable(Throwable):
// Exception with chaining-aware constructor
class HigherLevelException extends Exception {
HigherLevelException(Throwable cause) {
super(cause);
}
}
这篇关于Java中的异常翻译与异常链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!