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
Examples
try { thisFunctionDoesNotExist(); } 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 { thisFunctionDoesNotExist(); } 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