try-with-resources and null resource

Vimil Saju vimilsaju at yahoo.com
Mon Jan 31 11:51:42 PST 2011


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? 

--- On Fri, 1/28/11, Mark Thornton <mthornton at optrak.co.uk> wrote:

From: Mark Thornton <mthornton at optrak.co.uk>
Subject: Re: try-with-resources and null resource
To: coin-dev at openjdk.java.net
Date: Friday, January 28, 2011, 1:53 AM

On 28/01/2011 09:30, Florian Weimer wrote:
>
> By the way, has anybody else seen this phenomenon in their code base?
>
>    InputStream in = null;
>    try {
>      in = new FileInputStream(path);
>      useFile(in);
>    } finally {
>      if (in != null) {
>        in.close();
>      }
>    }
>
> I'm wondering where this is coming from.
>

In my experience, it arises where you have or might expect to extend to 
cases with more than one resource. You only need one try statement 
instead of a whole nest of them. Once you start doing this for the multi 
resource case I suspect there is a tendency to use the same style for 
single resources as well.

Mark Thornton





      


More information about the coin-dev mailing list