java编程之Exception handlers should preserve the original exception

2022-03-28 13:46:25 浏览数 (1)

捕捉到异常后, 原始异常的信息以及栈追溯信息应该被log下来或者向上传递,下面是一些关于java异常处理可能会出现问题的地方,希望对大家有所帮助!

不兼容代码例子:

代码语言:javascript复制
 // 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"); }

兼容代码例子:

代码语言:javascript复制
try { /* ... */ } catch (Exception e) { LOGGER.info(e); }   

try { /* ... */ } catch (Exception e) { throw new RuntimeException(e); }

try {
  /* ... */
} catch (RuntimeException e) {
  doSomething();
  throw e;
} catch (Exception e) {
  // Conversion into unchecked exception is also allowed
  throw new RuntimeException(e);
 }

e.getMessage获得的异常信息远不如直接通过logger.log(Level.SEVERE,"",异常对象)这个方式记录的信息全,强烈建议采用后者
来记录异常信息。

0 人点赞