当我们想要确保我们不会通过遇到break,continue或return语句而意外地绕过清理代码中使用的资源时,此块很有用:
HeavyProcess heavyProcess = new HeavyProcess();
try {
// ...
return heavyProcess.heavyTask();
} finally {
heavyProcess.doCleanUp();
}
此外,我们可能会面临无法在本地处理抛出异常的情况,或者我们希望当前方法在允许我们释放资源的同时仍然抛出异常:
public void doDangerousTask(Task task) throws ComplicatedException {
try {
// ...
task.gatherResources();
if (task.isComplicated()) {
throw new ComplicatedException("Too difficult");
}
// ...
} finally {
task.freeResources();
}
}