Try..catch..finally in JavaScript

colbygarland

Colby Garland

Posted on July 28, 2021

Try..catch..finally in JavaScript

Too often I find myself writing this type of code:

function cleanup(){ 
  // Doesn't matter what this does, it just needs 
  // to be run after the function is done doing the thing
}

function doTheThing(){
  try {
    // do something that could throw an error
    cleanup();
    return results;
  } catch(error) {
    // handle the error
    cleanup();
    return error;
  }
}

const result = doTheThing();
Enter fullscreen mode Exit fullscreen mode

Essentially, cleanup() needs to be ran regardless if our function was successful or not. Luckily, JS provides a nice way to do that for us 🥳

function cleanup(){ 
  // Doesn't matter what this does, it just needs 
  // to be run after the function is done doing the thing
}

function doTheThing(){
  try {
    // do something that could throw an error
    return results;
  } catch(error) {
    // handle the error
    return error;
  } finally {
    // the finally block gets run regardless of 
    // whether we had an error or not
    cleanup();
  }
}

const result = doTheThing();
Enter fullscreen mode Exit fullscreen mode

So using finally can clean up our code quite a bit!

💖 💪 🙅 🚩
colbygarland
Colby Garland

Posted on July 28, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related