Re: different try-finally approach
According to Pitch <mail@fake.info>:
So, my question is - why the extra coding in java? Am I missing
something?
There might be a confusion with a third pattern which looks like this:
// =====================================================================
public static int readFromFile(String name, byte[] buf, int off, int len)
throws MyException
{
InputStream in = null;
try {
in = new FileInputStream(name);
int orig = off;
while (len > 0) {
int rlen = in.read(buf, off, len);
if (rlen < 0)
break;
off += rlen;
len -= rlen;
}
return off - orig;
} catch (IOException ioe) {
throw new MyException(ioe);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
// ignored
}
}
}
}
// =====================================================================
The method above reads some bytes from a file. It is defined to throw a
custom exception (MyException) but _not_ a raw IOException. Since the
creation of a FileInputStream instance may throw such an exception, it
has to occur within the 'try' block, hence the use of the initialization
to 'null'.
The code above could be rewritten with a nested block:
// =====================================================================
public static int readFromFile(String name, byte[] buf, int off, int len)
throws MyException
{
try {
InputStream in = new FileInputStream(name);
try {
int orig = off;
while (len > 0) {
int rlen = in.read(buf, off, len);
if (rlen < 0)
break;
off += rlen;
len -= rlen;
}
return off - orig;
} finally {
in.close();
}
} catch (IOException ioe) {
throw new MyException(ioe);
}
}
// =====================================================================
However, that version does not perform _exactly_ the same thing (in case
the close() call throws an exception), and whether it is prettier than
the previous is, at best, arguable.
--Thomas Pornin