Re: different try-finally approach
In article <slrnh7de7u.8q5.avl@gamma.logic.tuwien.ac.at>,
avl@gamma.logic.tuwien.ac.at says...>
Pitch <mail@fake.info> wrote:
The first example ensures nothing more than the second one, right? If
the constructor throws an exception the "res" is null, so it can't be
closed anyways.
So, my question is - why the extra coding in java? Am I missing
something?
Yes, in that particular case those two snippets are equivalent.
Out of gut-feeling I'd still choose the first one (with "new" inside the
try-block), for reasons not covered by your outset.
When I see your code, I think: "some other day I will want to *catch*
those errors thrown from the 'new MyRessource()' line",
or "some day I *will* have more ressources, as in Bill's followup".
OK, but in such cases why not break up the code?
Look at this example:
public void copyFiles(String inFile, String outFile)
throws IOException
{
FileOutputStream outStream = null;
FileInputStream inStream = null;
try
{
FileOutputStream outStream = new FileOutputStream(outFile);
FileInputStream inStream = new FileInputStream(inFile);
// copying data...
}
finally
{
if (inStram != null) inStram.close();
if (outStram != null) outStram.close();
}
}
Now, look at this one:
public void copyFiles(String inFile, String outFile)
throws IOException
{
FileInputStream inStream = new FileInputStream(inFile);
try
{
copyToFile(inStream, outFile);
}
finally
{
inStram.close();
}
}
private void copyToFile(InputStream inStream, String outFile)
throws IOException
{
FileOutputStream outStream = new FileOutputStream(inFile);
try
{
// copying code...
}
finally
{
outStream.close();
}
}
Maybe you guys don't like writing as many methods? :)
--
de gustibus disputandum esse