Menu

#457 False -: CloseResource

open
nobody
None
5
2012-10-07
2006-03-06
No

I've been pointed at a false negative for the
CloseResource.

If a Statement is allocated in a loop, the try/catch
must be inthe same for loop - otherwise the statement
will not get closed.

A solution wasn't immediately obvious , but I've been
able to put together 2 JUnit tests. When added to
CloseResourceTest, they'll point out the problem.
TEST6_FAIL expects 1 failure, TEST7_OK expects 0.

private static final String TEST6_FAIL =
    "import java.sql.Statement;" + 
    "public class Foo {" + PMD.EOL +
    " void bar() {" + PMD.EOL +
    "  Connection c = pool.getConnection();" +

PMD.EOL +
" PreparedStatement stmt = null;" + PMD.EOL +
" try {" + PMD.EOL +
" for(int i = 0; i < 2; i++){" + PMD.EOL +
" stmt = c.createStatement();" + PMD.EOL +
" } " + PMD.EOL +
" } catch (Exception e) {" + PMD.EOL +
" } finally {" + PMD.EOL +
" stmt.close();" + PMD.EOL +
" c.close();" + PMD.EOL +
" }" + PMD.EOL +
" }" + PMD.EOL +
"}";

private static final String TEST7_OK =
    "import java.sql.Statement;" + 
    "public class Foo {" + PMD.EOL +
    " void bar() {" + PMD.EOL +
    "  Connection c = pool.getConnection();" +

PMD.EOL +
" PreparedStatement stmt = null;" + PMD.EOL +
" for(int i = 0; i < 2; i++){" + PMD.EOL +
" try {" + PMD.EOL +
" stmt = c.createStatement();" + PMD.EOL +
" } catch (Exception e) {" + PMD.EOL +
" } finally {" + PMD.EOL +
" stmt.close();" + PMD.EOL +
" c.close();" + PMD.EOL +
" }" + PMD.EOL +
" } " + PMD.EOL +
" }" + PMD.EOL +
"}";

I would imagine this would be an issue for all data
types that would be checked by CloseResource.

Discussion


Log in to post a comment.