Home » Programming » Javascript » Javascript Try Catch Finally

Using JavaScript try/catch/finally Statements [With Examples]

This tutorial explains how to use the try/catch/finally statements in Javascript to handle errors, with some useful examples.

Sometimes an error is expected – and rather than wanting the application to halt execution on the error; you want to do something else.

Other times, an error is unexpected or detrimental to the running of an application, and you want to make sure that it is reported.

try/catch statements in JavaScript let you do this.

try/catch will attempt to run a block of code and take a specified action if an error is met, rather than the default action (which usually halts code execution).

Syntax of try/catch/finally

try {
    // Code to be executed
catch [(exception_var)] {
    // Code to execute if an exception (error) is reached
finally {
    // Code to execute regardless of whether an exception was reached

Note that:

  • Either catch, or finally blocks should be supplied
  • exception_var should be the name of the variable you wish to use to access the exception thrown


try {
} catch (err) {
    console.error(err); // Print the error to the console.  
    // An error of type ReferenceError:  will be sent to the console as the code above tried to execute a non-existent function
    // Code execution will resume after the try/catch block rather than halting
} finally {
    console.log('Finished!'); // 'Finished!' will be sent to the console regardless of whether there was an error or not

Catching a Specific Type of Exception

You can handle different types of error differently by checking their type with instanceof:

try {
} catch (err) {

    if (err instanceof ReferenceError) {
        console.error(err); // Print the error to the console.  
    } else {
        console.log('An unexpected error occurred!');
        throw err;

Note that the error will only be output to the console if it is a ReferenceError. Otherwise, it is re-thrown to be treated using the default unhandled exception behavior – halting execution

Additional Resources

Mozilla technical documentation on try/catch

Not using JavaScript? Here’s how to use try/catch in PHP!

Photo of author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment