假设 Java6,此代码是否可以避免文件描述符泄漏:
{
InputStream in = fileObject.getReadStream();
// fileObject cleans it's internal state in case it throws exception
try {
// do whatever, possibly throwing exception
} finally {
try {
in.close();
} catch (Exception ex) {
// failure to close input stream is no problem
}
}
}
编辑:为了让问题看起来不那么明显,换句话说,上面的代码等于这个更长的代码:
{
InputStream in = null;
try {
in = fileObject.getReadStream();
// fileObject cleans it's internal state in case it throws exception
// do whatever, possibly throwing exception
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
// failure to close input stream is no problem
}
}
}
}
也就是说,对返回打开的流或抛出异常的方法的调用是紧接在 之前try
还是在try
块内是否重要?