30 Days Of JavaScript

Day 9: errors

Lesson 3: Finally

Try/Catch are really two legs of a three legged tripod. The full syntax is:

1try {
2  // try code
3} catch (error) {
4  // catch code
5} finally {
6  // finally code

try is where we run our potentially risky code.

catch is where we run and process any errors that get thrown

finally is always run regardless of if an error was thrown or not.

finally is our escape hatch. We might have done a number of things in our try block that need resetting and cleaning up with without an error being thrown. The most common use of finally is clearing some kind of loading indicator set at the start of our try that you want to reset no matter if there's an error or not. Here's an example

Uncomment the // throw new Error("Something went wrong"); line above and see that loading is still false at the end. If you take loading = false; out of the finally block and put it in the try block after the error is thrown then it will still be true.

This is a very common cause of website bugs and you've probably experienced it at some point where a loading overlay has appeared, something has gone wrong and then you are stuck with the loading overlay blocking the site. This will be because a developer forgot to use a finally to clear their loading flag.


Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co