Inside JavaScript
The finally Block
The finally statement contains statements to execute after the try and catch statements execute, but before the statements following the try and catch statements execute. The finally block executes whether or not an exception is thrown. (Note also that if an exception is thrown, the statements in the finally block execute even if no catch block handles the exception.) If you're working with some crucial resource that you've locked in your code and an error occurs, for instance, that resource may never be unlocked if the error prevents the full code from running. To make sure that the resource is freed whether or not an error occurred, you can put code to unlock the resource in the finally statement, which executes regardless of whether an exception is thrown. Here's an example: lockResource() try { useResource() } catch(e){ reportResourceError() } finally { unlockResource() } |