The finally
block contains statements to execute after the try
block and catch
block(s) execute, but before the statements following the try...catch...finally
block. Control flow will always enter the finally
block, which can proceed in one of the following ways:
- Immediately after the
try
block finishes execution normally (and no exceptions were thrown); - Immediately after the
catch
block finishes execution normally; - Immediately before a control-flow statement (
return
, throw
, break
, continue
) is executed in the try
block or catch
block.
If an exception is thrown from the try
block, even when there's no catch
block to handle the exception, the finally
block still executes, in which case the exception is still thrown immediately after the finally
block finishes executing.
The following example shows one use case for the finally
block. The code opens a file and then executes statements that use the file; the finally
block makes sure the file always closes after it is used even if an exception was thrown.
openMyFile();
try {
writeMyFile(theData);
} finally {
closeMyFile();
}
Control flow statements (return
, throw
, break
, continue
) in the finally
block will "mask" any completion value of the try
block or catch
block. In this example, the try
block tries to return 1, but before returning, the control flow is yielded to the finally
block first, so the finally
block's return value is returned instead.
function doIt() {
try {
return 1;
} finally {
return 2;
}
}
doIt();
It is generally a bad idea to have control flow statements in the finally
block. Only use it for cleanup code.