Java 为什么Findbugs无法检测我的代码错误?

Java 为什么Findbugs无法检测我的代码错误?,java,exception,findbugs,runtimeexception,Java,Exception,Findbugs,Runtimeexception,我读过findbugs网站上的bug检测器 我想编写一个测试代码,并使用Findbugs检测REC错误。 但findbugs不能。为什么?你能帮我解决这个问题吗 谢谢 以下是Findbugs中的描述 REC:未引发异常时捕获异常REC\U CATCH\U异常 此方法使用捕捉异常对象的try-catch块,但不会在try块内引发异常,也不会显式捕捉RuntimeException。一种常见的错误模式是说try{…}catch Exception e{something}作为捕获多种类型的异常的简写

我读过findbugs网站上的bug检测器

我想编写一个测试代码,并使用Findbugs检测REC错误。 但findbugs不能。为什么?你能帮我解决这个问题吗

谢谢

以下是Findbugs中的描述

REC:未引发异常时捕获异常REC\U CATCH\U异常

此方法使用捕捉异常对象的try-catch块,但不会在try块内引发异常,也不会显式捕捉RuntimeException。一种常见的错误模式是说try{…}catch Exception e{something}作为捕获多种类型的异常的简写,每个异常的捕获块都是相同的,但是这种构造也意外地捕获了RuntimeException,从而掩盖了潜在的错误

更好的方法是显式捕获抛出的特定异常,或者显式捕获RuntimeException异常,重新抛出它,然后捕获所有非运行时异常,如下所示:

try {
    ...
} catch (RuntimeException e) {
    throw e;
} catch (Exception e) {
    ... deal with all non-runtime exceptions ...
}
我的代码是:

公共静态无效测试1{

    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");
} 

}

请注意,FindBugs在.class文件上工作,因此编译器删除的内容(如未使用或无法访问的代码)对FindBugs不可见。您的try块将被删除,因为它不起任何作用。因此,对于测试,请始终构造实际执行的案例。谢谢,我如何编写Findbugs可以检测REC错误的示例代码?我在这段代码中使用Findbugs,但它仍然无法检测REC错误,我如何才能做到这一点?…因为您有catch异常,您必须只有针对非运行时异常的catch。