從 FingBugs的錯誤來看JAVA代碼質量(五)

REC_CATCH_EXCEPTION


[img]http://dl.iteye.com/upload/attachment/0067/9650/0226083e-a04e-35d1-a62c-36bd3321b683.jpg[/img]

[b]Bug: Exception is caught when Exception is not thrown
Pattern id: REC_CATCH_EXCEPTION, type: REC, category: STYLE[/b]

This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.

這想寫會無意中把RuntimeException也捕獲了,有可能導致潛在的bug。 JVM對RuntimeException有統一的捕獲機制,讓JVM來處理它。

在try/catch塊中捕獲異常,但是異常沒有在try語句中拋出而RuntimeException又沒有明確的被捕獲

1.比較推薦的寫法一般如下:
try {
}catch(IOException e){

}finally{
}

2.捕獲了異常,一定要處理異常
還有人在catch裏面什麼都不寫,就寫上

3.避免在大的語句塊裏面寫try,catch,因爲本身也比較耗費時間,而且不便於調試和發現問題。


[b]Bug: Call to equals() comparing different types
Pattern id: EC_UNRELATED_TYPES, type: EC, category: CORRECTNESS[/b]


[img]http://dl.iteye.com/upload/attachment/0067/9647/962578df-b808-35e4-9513-ad1cc72927f9.jpg[/img]

This method calls equals(Object) on two references of different class types with no common subclasses. Therefore, the objects being compared are unlikely to be members of the same class at runtime (unless some application classes were not analyzed, or dynamic class loading can occur at runtime). According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime.

兩個不同類型的對象調用equals,將永遠返回false,除非你重寫了equals方法。

調用equals方法比較不同類型的類

This method uses using pointer equality to compare two references that seem to be of different types. The result of this comparison will always be false at runtime.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章