写在前面
异常处理是代码中常见的处理,本文根据SonarQube在异常方面的规则和常见检查结果,选取说明了常见异常处理中的技术债务,提倡技术债务最少的编码方式。
Exception handlers should preserve the original exceptions
Either log or rethrow this exception.
When handling a caught exception, the original exception’s message and stack trace should be logged or passed forward.
NONCOMPLIANT CODE EXAMPLE
// Noncompliant - exception is lost
try { /* ... */ } catch (Exception e) { LOGGER.info("context"); }
// Noncompliant - exception is lost (only message is preserved)
try { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage()); }
// Noncompliant - exception is lost
try { /* ... */ } catch (Exception e) { throw new RuntimeException("context"); }
COMPLIANT SOLUTION
try { /* ... */ } catch (Exception e) { LOGGER.info(e); }
try { /* ... */ } catch (Exception e) { throw new RuntimeException(e); }
try {
/* ...