处理一个捕获的异常时,两个必须的信息必须被记录到日志里,或者放到重新抛出的异常中:
下列代码演示了这个规则:
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);
}
当所有异常的实例都需要处理时,但是一些特殊的实例不需要处理,就必须使用传播。 这个规则允许使用传播方式。
比如,下面的代码记录了所有非RuntimeException的Exception.
所有RuntimeException会继续向上传播。
try {
/* ... */
} catch (RuntimeException e) { // Compliant - propagation of the specific exception
throw e;
} catch (Exception e) { // Compliant - catching of the general exception
LOGGER.error("...", e);
}
这个规则也允许把checked异常转换为unchecked异常来继续向上传播。
try {
/* ... */
} catch (IOException e) { // Compliant - propagation of checked exception by encapsulating it into an unchecked exception
throw new MyRuntimeException(e);
}