<分区>
举个例子:
public List<CloseableThing> readThings(List<File> files) throws IOException {
ImmutableList.Builder<CloseableThing> things = ImmutableList.builder();
try {
for (File file : files) {
things.add(readThing(file))
}
return things.build();
} catch (Throwable t) {
for (CloseableThing thing : things.build()) {
thing.close();
}
throw t;
}
}
一个code review评论进来了,因为一般有规定不抓Throwable。进行这种仅失败清理的旧模式是:
public List<CloseableThing> readThings(List<File> files) throws IOException {
ImmutableList.Builder<CloseableThing> things = ImmutableList.builder();
boolean success = false;
try {
for (File file : files) {
things.add(readThing(file))
}
success = true;
return things.build();
} finally {
if (!success) {
for (CloseableThing thing : things.build()) {
thing.close();
}
}
}
}
我觉得这有点乱,不完全理解它与捕获 Throwable 是否有任何不同。在任何一种情况下,异常都会传播。在任何一种情况下,当可能发生 OutOfMemoryError 时,都会运行其他代码。
那么最后真的更安全了吗?