finally Block
The finally block is executed regardless of whether the try block ends normally, throws an exception, or returns early. It is typically used for "cleanup" tasks such as releasing resources, closing files, and resetting state.
The execution order is: try block → catch block (if an exception is thrown and caught) → finally block. Even if there is a return statement in the catch block, finally will execute before the return.
The code on the right demonstrates three scenarios: normal execution, throwing an exception, and early return in the catch block. Note that the finally block executes in every case.
Note
Avoid throwing exceptions in
finally blocks, as this will mask the original exception.Try commenting out the throw statement in riskyOperation and observe the behavior of finally during normal execution.