-1

I have read the bug detectors in findbugs website, http://findbugs.sourceforge.net/bugDescriptions.html

I want to write a test code and use Findbugs to detect the REC error. But the findbugs cannot. Why? Could you help me to solve this?

Thanks,

Below is the description in Findbugs.

REC: Exception is caught when Exception is not thrown (REC_CATCH_EXCEPTION)

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.

A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:

try {
    ...
} catch (RuntimeException e) {
    throw e;
} catch (Exception e) {
    ... deal with all non-runtime exceptions ...
}

My code is:

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

}
webuster
  • 2,490
  • 18
  • 27
user3408277
  • 11
  • 1
  • 1
  • Note that FindBugs works on the .class files, so stuff that the compiler removes, such as unused or unreachable code, will not be visible to FindBugs. Your try-block will be removed because it does nothing. So for testing, always construct cases that actually execute. – barfuin Mar 11 '14 at 23:53
  • Thanks, How can I write a sample code that Findbugs can detect the REC error? – user3408277 Mar 14 '14 at 00:41

1 Answers1

3

The try is where the exception occur that you want to catch. However, since it is occurring out of the try block, the exception is not caught by the catch part, which is why FindBugs reporting it as a useless try {...} catch {...} code. The proper code should be as follows.

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

}

Christopher Z
  • 899
  • 1
  • 12
  • 32