Exception handling statements
You can throw exceptions using the throw statement and handle them using
the try...catch statements.
Exception types
Just about any object can be thrown in JavaScript. Nevertheless, not all thrown objects are created equal. While it is common to throw numbers or strings as errors, it is frequently more effective to use one of the exception types specifically created for this purpose:
throw statement
Use the throw statement to throw an exception. A throw
statement specifies the value to be thrown:
throw expression;
You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:
throw "Error2"; // String type
throw 42; // Number type
throw true; // Boolean type
throw {
toString() {
return "I'm an object!";
},
};try...catch statement
The try...catch statement marks a block of statements to try, and
specifies one or more responses should an exception be thrown. If an exception is
thrown, the try...catch statement catches it.
The try...catch statement consists of a try block, which
contains one or more statements, and a catch block, containing statements
that specify what to do if an exception is thrown in the try block.
In other words, you want the try block to succeed—but if it does not, you
want control to pass to the catch block. If any statement within the
try block (or in a function called from within the try block)
throws an exception, control immediately shifts to the catch
block. If no exception is thrown in the try block, the catch
block is skipped. The finally block executes after the try and
catch blocks execute but before the statements following the
try...catch statement.
The following example uses a try...catch statement. The example calls a
function that retrieves a month name from an array based on the value passed to the
function. If the value does not correspond to a month number
(1 – 12), an exception is thrown with the value
'Invalid month code' and the statements in the catch block set the
monthName variable to 'unknown'.
function getMonthName(mo) {
mo--; // Adjust month number for array index (so that 0 = Jan, 11 = Dec)
// prettier-ignore
const months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
if (!months[mo]) {
throw new Error("Invalid month code"); // throw keyword is used here
}
return months[mo];
}
try {
// statements to try
monthName = getMonthName(myMonth); // function could throw exception
} catch (e) {
monthName = "unknown";
logMyErrors(e); // pass exception object to error handler (i.e. your own function)
}
The catch block
You can use a catch block to handle all exceptions that may be generated
in the try block.
catch (exception) {
statements
}
The catch block specifies an identifier (exception
in the preceding syntax) that holds the value specified by the throw
statement. You can use this identifier to get information about the exception that was
thrown.
JavaScript creates this identifier when the catch block is entered. The
identifier lasts only for the duration of the catch block. Once the
catch block finishes executing, the identifier no longer exists.
For example, the following code throws an exception. When the exception occurs, control
transfers to the catch block.
try {
throw "myException"; // generates an exception
} catch (err) {
// statements to handle any exceptions
logMyErrors(err); // pass exception object to error handler
}
Note:
When logging errors to the console inside
a catch block, using console.error() rather than
console.log() is advised for debugging. It formats the message as an
error, and adds it to the list of error messages generated by the page.
The finally block
The finally block contains statements to be executed after the
try and catch blocks execute. Additionally, the
finally block executes before the code that follows the
try...catch...finally statement.
It is also important to note that the finally block will execute
whether or not an exception is thrown. If an exception is thrown, however, the
statements in the finally block execute even if no catch block
handles the exception that was thrown.
You can use the finally block to make your script fail gracefully when an
exception occurs. For example, you may need to release a resource that your script has
tied up.
The following example opens a file and then executes statements that use the file.
(Server-side JavaScript allows you to access files.) If an exception is thrown while the
file is open, the finally block closes the file before the script fails.
Using finally here ensures that the file is never left open, even
if an error occurs.
openMyFile();
try {
writeMyFile(theData); // This may throw an error
} catch (e) {
handleError(e); // If an error occurred, handle it
} finally {
closeMyFile(); // Always close the resource
}
If the finally block returns a value, this value becomes the return value
of the entire try...catch...finally production, regardless of any
return statements in the try and catch blocks:
function f() {
try {
console.log(0);
throw "bogus";
} catch (e) {
console.log(1);
// This return statement is suspended
// until finally block has completed
return true;
console.log(2); // not reachable
} finally {
console.log(3);
return false; // overwrites the previous "return"
// `f` exits here
console.log(4); // not reachable
}
console.log(5); // not reachable
}
console.log(f()); // 0, 1, 3, false
Overwriting of return values by the finally block also applies to
exceptions thrown or re-thrown inside of the catch block:
function f() {
try {
throw "bogus";
} catch (e) {
console.log('caught inner "bogus"');
// This throw statement is suspended until
// finally block has completed
throw e;
} finally {
return false; // overwrites the previous "throw"
// `f` exits here
}
}
try {
console.log(f());
} catch (e) {
// this is never reached!
// while f() executes, the `finally` block returns false,
// which overwrites the `throw` inside the above `catch`
console.log('caught outer "bogus"');
}
// Logs:
// caught inner "bogus"
// false
Nesting try...catch statements
You can nest one or more try...catch statements.
If an inner try block does not have a corresponding
catch block:
- it must contain a
finallyblock, and - the enclosing
try...catchstatement'scatchblock is checked for a match.
For more information, see nested try-blocks
on the try...catch
reference page.
Utilizing Error objects
Depending on the type of error, you may be able to use the name and
message properties to get a more refined message.
The name property provides the general class of Error (such
as DOMException or Error), while message
generally provides a more succinct message than one would get by converting the error
object to a string.
If you are throwing your own exceptions, in order to take advantage of these properties
(such as if your catch block doesn't discriminate between your own
exceptions and system ones), you can use the Error constructor.
For example:
function doSomethingErrorProne() {
if (ourCodeMakesAMistake()) {
throw new Error("The message");
}
doSomethingToGetAJavaScriptError();
}
try {
doSomethingErrorProne();
} catch (e) {
// Now, we actually use `console.error()`
console.error(e.name); // 'Error'
console.error(e.message); // 'The message', or a JavaScript error message
}