DEV Community

Colby Garland
Colby Garland

Posted on

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!

Top comments (0)