Exception handlers should provide some context and preserve the original exception
处理异常时,需要进行两个操作: 1、使用context减缓复制的问题 2、保留原始异常信息,进行堆栈问题的追踪( stack trace )
看一些例子:
try { /* ... */ } catch (Exception e) { LOGGER.info("context"); } // Non-Compliant - exception is lost
try { /* ... */ } catch (Exception e) { LOGGER.info(e); } // Non-Compliant - context is required
try { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage()); } // Non-Compliant - exception is lost (only message is preserved)
try { /* ... */ } catch (Exception e) { LOGGER.info("context", e); } // Compliant(符合规范)
try {
/* ... */
} catch (Exception e) { // Non-Compliant - exception is lost
throw new RuntimeException("context");
}
try {
/* ... */
} catch (Exception e) { // Compliant
throw new RuntimeException("context", e);
}
|
一般性的异常,所有问题都必须要处理,但是对于一些特殊的异常,必须使用传播( propagation ),而且这时的传播是允许的。
try {
/* ... */
} catch (RuntimeException e) { // Compliant - propagation of the specific exception
throw e;
} catch (Exception e) { // Compliant - catching of the general exception
LOGGER.error("...", e);
}
|
受控制的Exception转换成Runtime Exception减缓受控异常的传播。
try {
/* ... */
} catch (IOException e) { // Compliant - propagation of checked exception by encapsulating it into an unchecked exception
throw new MyRuntimeException(e);
}
|
不管是log还是重新抛出异常都伴随着context的信息。