Will it finally: a try/catch quiz

You know how try and catch work, but what about finally? Does it run after rethrown exceptions or return statements?

4th February, 2019

With the advent of async/await, I’ve recently found myself using a lot more try/catch/finally in my code. But honestly, I’m a little out of practice with finally. When I went to actually use it, I was a little unsure of its finer details. So I put together a few examples.

So finally lets you clean up after yourself when exceptions occur. But what about when nothing goes wrong and you just return from the function like normal… in a try block?

Take a look at the below example. Is it possible that the finally block within example() can run after you’ve already hit a return statement? Uncomment the example() at the bottom of the editor to find out!

Frontend Armory is a statically rendered website; it’s built with a tool called Navi, which lets you configure a renderPageToString() function that will be used to render each page.

In order to make sure each call to renderPageToString() is independent of the previous one, Navi uses try/catch/finally and some obscure node-fu to unload any modules that are loaded during the rendering process.

You can take a look at the full source for Navi’s static renderer on GitHub

As you can see from the above example, try/catch/finally also work great with JavaScript’s new async/await syntax. So if this has reminded you that you need to brush up on async/await, now’s the time to mosey on over to my Mastering Asynchronous JavaScript course!

But that’s it for today. Thanks so much for reading! If you have any questions or comments, shoot me a Tweet or DM at @james_k_nelson. And until next time, happy coding :-)

Go Pro

Stay in the loop.

Keeping up to date with React is a full time job that pays only in frustration. Luckily, you can delegate! Just become a free member, and we'll keep you up to date with our monthly newsletter.