Stupid CFML Tricks: Run After Return

This article was originally focused on CFML and erroneously claimed that you could execute code after a return statement by putting it in the finally block of a try/finally statement. What follows is what I've since learned about how try/catch/finally works. Thanks to Sean Corfield for educating me on how I originally understood this incorrectly.

When I first learned about try/catch/finally, everything made perfect sense to me. The try block executes; if there's an error it's handled by the catch block, and then if there's a finally block then it is executed after the try block (if successful) or after the catch block (if an error was thrown in the try block).

Now let's make things interesting! What happens when your try block contains a return statement?

const example = () => {
let x = 1;
try {
return x;
} finally {
x = 2;
console.log('inside finally! x=', x);
}
};

console.log(example());

Without testing it, what do you think happens? Does the function return 1 or 2?

As it turns out, the function returns 1; but first it logs that x=2.

This makes sense because the sequence of events is:

Using finally is shorthand for copy+pasting the contents of the finally block to precede all possible exit statements (return, throw) inside the try block.

Webmentions

It's like comments, but you do it on Twitter.

1 Reply

Adam Cameron Adam Cameron
adamtuttle.codes/blog/2017/2017…
Add your comment: Tweet about this article.

Webmentions via webmention.io.

Discuss on TwitterEdit on GitHubContributions