程序員的成長之路
互聯網/程序員/技術/資料共享
閱讀本文大概需要 5 分鐘。
來自:https://www.rowkey.me/blog/2017/09/17/java-exception/
在Java中處理異常並不是一個簡單的事情。不僅僅初學者很難理解,即使一些有經驗的開發者也需要花費很多時間來思考如何處理異常,包括需要處理哪些異常,怎樣處理等等。
這也是絕大多數開發團隊都會制定一些規則來規範對異常的處理的原因。而團隊之間的這些規範往往是截然不同的。
本文給出幾個被很多團隊使用的異常處理最佳實踐。
1. 在Finally塊中清理資源或者使用try-with-resource語句
當使用類似InputStream這種需要使用後關閉的資源時,一個常見的錯誤就是在try塊的最後關閉資源。
public void doNotCloseResourceInTry() {
FileInputStream inputStream = null;
try {
File file = new File("./tmp.txt");
inputStream = new FileInputStream(file);
// use the inputStream to read a file
// do NOT do this
inputStream.close();
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
}
上述代碼在沒有任何exception的時候運行是沒有問題的。但是當try塊中的語句拋出異常或者自己實現的代碼拋出異常,那麼就不會執行最後的關閉語句,從而資源也無法釋放。
合理的做法則是將所有清理的代碼都放到finally塊中或者使用try-with-resource語句。
public void closeResourceInFinally() {
FileInputStream inputStream = null;
try {
File file = new File("./tmp.txt");
inputStream = new FileInputStream(file);
// use the inputStream to read a file
} catch (FileNotFoundException e) {
log.error(e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error(e);
}
}
}
}
public void automaticallyCloseResource() {
File file = new File("./tmp.txt");
try (FileInputStream inputStream = new FileInputStream(file);) {
// use the inputStream to read a file
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
}
2. 指定具體的異常
儘可能的使用最具體的異常來聲明方法,這樣才能使得代碼更容易理解。
public void doNotDoThis() throws Exception {
...
}
public void doThis() throws NumberFormatException {
...
}
如上,NumberFormatException字面上即可以看出是數字格式化錯誤。
3. 對異常進行文檔說明
當在方法上聲明拋出異常時,也需要進行文檔說明。和前面的一點一樣,都是爲了給調用者提供儘可能多的信息,從而可以更好地避免/處理異常。
在Javadoc中加入throws聲明,並且描述拋出異常的場景。
/**
* This method does something extremely useful ...
*
* @param input
* @throws MyBusinessException if ... happens
*/
public void doSomething(String input) throws MyBusinessException {
...
}
4. 拋出異常的時候包含描述信息
在拋出異常時,需要儘可能精確地描述問題和相關信息,這樣無論是打印到日誌中還是監控工具中,都能夠更容易被人閱讀,從而可以更好地定位具體錯誤信息、錯誤的嚴重程度等。
但這裏並不是說要對錯誤信息長篇大論,因爲本來Exception的類名就能夠反映錯誤的原因,因此只需要用一到兩句話描述即可。
try {
new Long("xyz");
} catch (NumberFormatException e) {
log.error(e);
}
NumberFormatException即告訴了這個異常是格式化錯誤,異常的額外信息只需要提供這個錯誤字符串即可。當異常的名稱不夠明顯的時候,則需要提供儘可能具體的錯誤信息。
5. 首先捕獲最具體的異常
現在很多IDE都能智能提示這個最佳實踐,當你試圖首先捕獲最籠統的異常時,會提示不能達到的代碼。
當有多個catch塊中,按照捕獲順序只有第一個匹配到的catch塊才能執行。因此,如果先捕獲IllegalArgumentException,那麼則無法運行到對NumberFormatException的捕獲。
public void catchMostSpecificExceptionFirst() {
try {
doSomething("A message");
} catch (NumberFormatException e) {
log.error(e);
} catch (IllegalArgumentException e) {
log.error(e)
}
}
6. 不要捕獲Throwable
Throwable是所有異常和錯誤的父類。你可以在catch語句中捕獲,但是永遠不要這麼做。
如果catch了throwable,那麼不僅僅會捕獲所有exception,還會捕獲error。而error是表明無法恢復的jvm錯誤。因此除非絕對肯定能夠處理或者被要求處理error,不要捕獲throwable。
public void doNotCatchThrowable() {
try {
// do something
} catch (Throwable t) {
// don't do this!
}
}
7. 不要忽略異常
很多時候,開發者很有自信不會拋出異常,因此寫了一個catch塊,但是沒有做任何處理或者記錄日誌。
public void doNotIgnoreExceptions() {
try {
// do something
} catch (NumberFormatException e) {
// this will never happen
}
}
但現實是經常會出現無法預料的異常或者無法確定這裏的代碼未來是不是會改動(刪除了阻止異常拋出的代碼),而此時由於異常被捕獲,使得無法拿到足夠的錯誤信息來定位問題。
合理的做法是至少要記錄異常的信息。
public void logAnException() {
try {
// do something
} catch (NumberFormatException e) {
log.error("This should never happen: " + e);
}
}
8. 不要記錄並拋出異常
可以發現很多代碼甚至類庫中都會有捕獲異常、記錄日誌並再次拋出的邏輯。如下:
try {
new Long("xyz");
} catch (NumberFormatException e) {
log.error(e);
throw e;
}
這個處理邏輯看着是合理的。但這經常會給同一個異常輸出多條日誌。如下:
17:44:28,945 ERROR TestExceptionHandling:65 - java.lang.NumberFormatException: For input string: "xyz"
Exception in thread "main" java.lang.NumberFormatException: For input string: "xyz"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.(Long.java:965)
at com.stackify.example.TestExceptionHandling.logAndThrowException(TestExceptionHandling.java:63)
at com.stackify.example.TestExceptionHandling.main(TestExceptionHandling.java:58)
如上所示,後面的日誌也沒有附加更有用的信息。如果想要提供更加有用的信息,那麼可以將異常包裝爲自定義異常。
public void wrapException(String input) throws MyBusinessException {
try {
// do something
} catch (NumberFormatException e) {
throw new MyBusinessException("A message that describes the error.", e);
}
}
因此,僅僅當想要處理異常時纔去捕獲,否則只需要在方法簽名中聲明讓調用者去處理。
9. 包裝異常時不要拋棄原始的異常
捕獲標準異常幷包裝爲自定義異常是一個很常見的做法。這樣可以添加更爲具體的異常信息並能夠做針對的異常處理。
需要注意的是,包裝異常時,一定要把原始的異常設置爲cause(Exception有構造方法可以傳入cause)。否則,丟失了原始的異常信息會讓錯誤的分析變得困難。
public void wrapException(String input) throws MyBusinessException {
try {
// do something
} catch (NumberFormatException e) {
throw new MyBusinessException("A message that describes the error.", e);
}
}
總結
綜上可知,當拋出或者捕獲異常時,有很多不一樣的東西需要考慮。其中的許多點都是爲了提升代碼的可閱讀性或者api的可用性。
異常不僅僅是一個錯誤控制機制,也是一個溝通媒介,因此與你的協作者討論這些最佳實踐並制定一些規範能夠讓每個人都理解相關的通用概念並且能夠按照同樣的方式使用它們。
<END>
推薦閱讀:
一個依賴搞定 Spring Boot 反爬蟲,防止接口盜刷!
5T技術資源大放送!包括但不限於:C/C++,Linux,Python,Java,PHP,人工智能,單片機,樹莓派,等等。在公衆號內回覆「2048」,即可免費獲取!!
微信掃描二維碼,關注我的公衆號
寫留言
朕已閱