系列文章目錄
文章目錄
- 系列文章目錄
- 前言
- 一、忽略所有異常
- 二、重復包裝RuntimeException
- 三、不正確的傳播異常
- 四、用日志記錄異常
- 五、異常處理不徹底
前言
前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到網站,這篇文章男女通用,看懂了就去分享給你的碼吧。
一、忽略所有異常
錯誤的寫法:
try {
doStuff();
} catch(Exception e) {
log.fatal("Could not do stuff");
}
doMoreStuff();
這個代碼有兩個問題, 一個是沒有告訴調用者, 系統調用出錯了. 第二個是日志沒有出錯原因, 很難跟蹤定位問題。
正確的寫法:
try {
doStuff();
} catch(Exception e) {
throw new MyRuntimeException("Could not do stuff because: "+ e.getMessage, e);
}
二、重復包裝RuntimeException
錯誤的寫法:
try {
doStuff();
} catch(Exception e) {
throw new RuntimeException(e);
}
正確的寫法:
try {
doStuff();
} catch(RuntimeException e) {
throw e;
} catch(Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
try {
doStuff();
} catch(IOException e) {
throw new RuntimeException(e.getMessage(), e);
} catch(NamingException e) {
throw new RuntimeException(e.getMessage(), e);
}
三、不正確的傳播異常
錯誤的寫法:
try {
} catch(ParseException e) {
throw new RuntimeException();
throw new RuntimeException(e.toString());
throw new RuntimeException(e.getMessage());
throw new RuntimeException(e);
}
主要是沒有正確的將內部的錯誤信息傳遞給調用者. 第一個完全丟掉了內部錯誤信息, 第二個錯誤信息依賴toString方法, 如果沒有包含最終的嵌套錯誤信息, 也會出現丟失, 而且可讀性差. 第三個稍微好一些, 第四個跟第二個一樣。
正確的寫法:
try {
} catch(ParseException e) {
throw new RuntimeException(e.getMessage(), e);
}
四、用日志記錄異常
錯誤的寫法:
try {
...
} catch(ExceptionA e) {
log.error(e.getMessage(), e);
throw e;
} catch(ExceptionB e) {
log.error(e.getMessage(), e);
throw e;
}
一般情況下在日志中記錄異常是不必要的, 除非調用方沒有記錄日志。
五、異常處理不徹底
錯誤的寫法:
try {
is = new FileInputStream(inFile);
os = new FileOutputStream(outFile);
} finally {
try {
is.close();
os.close();
} catch(IOException e) {
/* we can't do anything */
}
}
is可能close失敗, 導致os沒有close
正確的寫法:
try {
is = new FileInputStream(inFile);
os = new FileOutputStream(outFile);
} finally {
try { if (is != null) is.close(); } catch(IOException e) {/* we can't do anything */}
try { if (os != null) os.close(); } catch(IOException e) {/* we can't do anything */}
}