简体   繁体   中英

Dead code warning in Eclipse - is this a bug in Eclipse? Or me overlooking something obvious?

With this (simplified) code example Eclipse (Kepler SR2) gives a warning for the innermost if-statement (if (con != null)) , dead code .

public class DbManager {
    public String getSingleString(String query) throws SQLException {
        DbManager dbmgr = new DbManager();
        Connection con = null;
        try {
            con = dbmgr.getConnection("user", "pwd", URL);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
            if (con != null) {
                PreparedStatement pstmt = null;
                ResultSet rset = null;
                pstmt = con.prepareStatement(query.toString());
                rset = pstmt.executeQuery();
            if (rset != null && rset.next()) {
                return (rset.getString(1));
            }
        }
    }
return null;
}

Typically the database connection defined on the line after the try will create a connection and then the offending if-statement will be true. Is the warning about dead code really correct?

If dbmgr.getConnection("user", "pwd", URL); returns an exception, then con will never get assigned a non-null reference.

You initialized con with null. So when an exception will be thrown and your code will reach the catch, con will be null. That is why that check (con != null) does not make sense.

If the connection is successfully created, then that catch statement will never be called so it is dead code, try rearranging it to:

try {
    con = dbmgr.getConnection("user", "pwd", URL);
    //if (con != null) { <-- not required because of the try and catch
    PreparedStatement pstmt = null;
    ResultSet rset = null;
    pstmt = con.prepareStatement(query.toString());
    rset = pstmt.executeQuery();
    if (rset != null && rset.next()) {
        return (rset.getString(1));
    }
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (SQLException e) {
    e.printStackTrace();
}

I realised the problem after running the code a couple of times and bumping into some problems: one } was missing after the catch. It should be:

try {
    con = dbmgr.getConnection("cap_x1", "test");
} catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    if (con != null) {
        PreparedStatement pstmt = null;
        ResultSet rset = null;

etc. Thank you for your feedback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM