try-with-resources and null resource

Tom Hawtin tom.hawtin at oracle.com
Mon Jan 31 12:26:14 PST 2011


On 31/01/2011 19:51, Vimil Saju wrote:
> The following code pattern is present at many places in our code base.
> 	List<T>  records = new ArrayList<T>();	ResultSet rs = null;
> 	try {		rs = executeQuery(st);		records = fetchRecords(rs, returnClass);	}	catch(Exception ex) {		logDBError(ex);		throw new DBException(ErrorCodes.DB_FETCH_ERROR, ex);	}	finally {		freeUp(rs);	}
> 	return records;
> How would the about code look like with the new try-with-resources syntax?

Looks like copy-and-paste messed up the formatting:

    List<T> records = new ArrayList<T>();
    ResultSet rs = null;
    try {
        rs = executeQuery(st);
        records = fetchRecords(rs, returnClass);
    } catch (Exception ex) {
        logDBError(ex);
        throw new DBException(ErrorCodes.DB_FETCH_ERROR, ex);
    } finally {
        freeUp(rs);
    }
    return records;

I'm going to assume that executeQuery does not return null and that 
freeUp closes the ResultSet if non-null and wraps the SQLException as a 
DBException.

    try {
        try (ResultSet rs = executeQuery(st)) {
            return fetchRecords(rs, returnClass);
        }
    } catch (Exception ex) {
        logDBError(ex);
        throw new DBException(ErrorCodes.DB_FETCH_ERROR, ex);
    }

(I've left catch Exception in, although usually such a broad catch would 
be considered a bad idea in most situations.)

The Execute Around idiom is still a good idea. A better idea when we 
have concise anonymous inner class syntax/lambdas. (Or an ORM!)

Tom



More information about the coin-dev mailing list