Try-Finally in Javascript
The usefulness of the try {} finally {}
should not be under-estimated. You do so at your peril. For it is little used, and often misunderstood.
It was introduced in common programming languages of the mid 1980s, where a cleanup mechanism was required for error handling, to be executed whether an exception occurred or not.
Synchronous Promises?
You’ll notice a striking parallel with the common javascript Promise
. Albeit a synchronous
one. Where control of flow can be segmented into 3 execution groups: resolved
, rejected
and doAlways.
Although this gives us a basic Promise signature, it’s usefulness is not immediately apparent.
Dropping the Catch
But without the catch, it gives us the pretty unique ability, of deferring the execution of code, and warping the control of flow.
Consider the following example:
So what do we expect the output from 1, 2 and 3 to be? Well, it doesn’t take a genius to work out we’re going to see James
, Simon
, Bob
in the console, but what might surprise you is the full log:
1) Name is James
> returning Simon
> assigning bob
2) Name is Simon
3) Name is Bob
The interesting thing to notice here, is the code execution order. First return n
is executed. At this point one would expect console.log #2 to process that return result, but it does not.
The next line to be executed is name = 'Bob'.
Followed by what would usually have happened from the return of a method invocation.
Putting it to use
So, it’s clear that using try {} finally {}
we can interrupt the call stack, to execute arbitrary code. But what possible uses could this present to us?
Well certainly we can use for the purpose for which it was designed: cleaning up resources that were allocated in the try
block. But we could also extend it’s exception handling, to persist application errors to a remote endpoint. Or opening a stream and then passing that stream to an inner method to be loaded, using the finally clause to ensure that the stream is closed regardless of the success or failure of the read.