[英]Why Findbugs cannot detect my code error?
我已經在findbugs網站( http://findbugs.sourceforge.net/bugDescriptions.html)上閱讀了錯誤檢測器。
我想編寫一個測試代碼,並使用Findbugs檢測REC錯誤。 但是findbugs不能。 為什么? 你能幫我解決這個問題嗎?
謝謝,
以下是Findbugs中的描述。
REC:未引發異常時捕獲異常(REC_CATCH_EXCEPTION)
此方法使用一個try-catch塊來捕獲Exception對象,但是在try塊內不會引發Exception,並且不會顯式捕獲RuntimeException。 嘗試將{{} catch(Exception e){something}作為捕獲多種異常類型的簡寫是一種常見的錯誤模式,每種異常類型的捕獲塊相同,但是這種構造也偶然捕獲了RuntimeException。 ,掩蓋潛在的錯誤。
更好的方法是顯式捕獲拋出的特定異常,或者顯式捕獲RuntimeException異常,將其重新拋出,然后捕獲所有非Runtime異常,如下所示:
try {
...
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
... deal with all non-runtime exceptions ...
}
我的代碼是:
公共靜態無效性test1(){
int A[] = {1,2,3};
int result = 5/0;//divided by 0
int arrOut = A[0]+A[4];//index out of bound
System.out.println(arrOut);
System.out.println(result);
try {
} catch (RuntimeException e) {
// TODO: handle exception
System.out.println("Runtimeex throw");
throw e;
} catch (Exception e) {
// TODO: handle exception
System.out.println("An try error occurred: 0 cannot be divided");
}
}
try
是要捕獲異常的地方。 但是,由於它是在try
塊之外發生的,因此catch部分不會捕獲該異常,這就是為什么FindBugs將其報告為無用的try {...} catch {...}
代碼的原因。 正確的代碼應如下所示。
int A[] = {1,2,3};
try {
int result = 5/0;//divided by 0
int arrOut = A[0]+A[4];//index out of bound
System.out.println(arrOut);
System.out.println(result);
} catch (RuntimeException e) {
// TODO: handle exception
System.out.println("Runtimeex throw");
throw e;
} catch (Exception e) {
// TODO: handle exception
System.out.println("An try error occurred: 0 cannot be divided");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.