Try..catch..finally in JavaScript
Colby Garland
Posted on July 28, 2021
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();
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();
So using finally
can clean up our code quite a bit!
💖 💪 🙅 🚩
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
tailwindcss Integrating Tailwind CSS with Other Frontend Frameworks for Admin Panels
November 30, 2024