Java – if an exception is thrown, ensure that the object is closed

I'm creating JDBC statements and resultset

Findbugs correctly points out that if exceptions are thrown, I won't close them

So now I have:

Statement stmt = null;
ResultSet res = null;
try {
    stmt = ...
    res = stmt.executeQuery(...);
    ...
} finally {
    try {
        if(res != null)
           res.close(); // <-- can throw sqlException
    } finally {
        if(stmt != null)
           stmt.close();
    }
}

(only I have more result sets and prepared statements... So my last nest is quite deep)

Must there be a better way to ensure that a large number of result sets are closed?

(Narrator: in Symbian, they will never let the destructor / close / release / Remove - type method throw any errors. I think this is a very good design decision. In my opinion, all closed methods in JDBC throw sqlexceptions, which will make things unnecessary complicated.)

Solution

If you are using java 7, you can use resultset to extend the fact of autoclosable and use the try with resources statement

try (Statement sql = <WHATEVER>;
     ResultsSet res = sql.executeQuery(<WHATEVER>)) {
     // Use results
}

At least you avoided the finally clause

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>