Try...Catch, Errors, & Exceptions
When something goes wrong at run time, JavaScript throws an exception: it stops running the current code and looks back through the functions that led there for a catch block to handle it. If it finds none, the error is reported and the script stops. A try...catch statement marks the code that might fail and says what to do if it does.
try { // code that might throw} catch (err) { // runs only if something in try threw} finally { // runs in either case}Use it around operations whose failure the program can recover from, such as parsing data from outside, reading saved settings or calling a server. It is not a substitute for checking values that the code can test in advance.
Catching an error
Section titled “Catching an error”JSON.parse() throws a SyntaxError when its input is not valid JSON, which makes it a common reason for a try block. The error object has a name that gives its type and a message that describes the problem.
const saved = '{"theme": "dark", "fontSize": 16';
try { const settings = JSON.parse(saved); console.log('Loaded', settings.theme);} catch (err) { console.log(err.name); console.log(err.message);} finally { console.log('Finished reading settings');}console.log('The program carries on');This prints:
SyntaxErrorExpected ',' or '}' after property value in JSON at position 32 (line 1 column 33)Finished reading settingsThe program carries onThe console.log('Loaded', …) line never runs, because execution jumps to catch at the moment JSON.parse() throws. After the catch block, the program continues normally. The wording of message comes from the engine and varies between browsers, so code should test name or the error’s type rather than the message.
Error objects also have a stack property, which lists the function calls that led to the error and is what the console shows for an uncaught one.
Throwing errors
Section titled “Throwing errors”throw raises an exception of your own. It can throw any value, but throw an Error object or one of its subtypes, because only those carry a stack and the name and message that other code expects.
const setQuantity = (quantity) => { if (!Number.isInteger(quantity)) { throw new TypeError(`Quantity must be a whole number, not ${quantity}`); } if (quantity < 1 || quantity > 10) { throw new RangeError(`Quantity must be between 1 and 10, not ${quantity}`); } return quantity;};
for (const value of [3, 2.5, 40]) { try { console.log('Set to', setQuantity(value)); } catch (err) { console.log(`${err.name}: ${err.message}`); }}This prints:
Set to 3TypeError: Quantity must be a whole number, not 2.5RangeError: Quantity must be between 1 and 10, not 40The built-in error types
Section titled “The built-in error types”| Type | Thrown when |
|---|---|
Error |
the base type, used for general errors |
TypeError |
a value is of the wrong type, as when calling something that is not a function or reading a property of undefined |
RangeError |
a number is outside the allowed range, as in new Array(-1) |
ReferenceError |
the code uses a variable that does not exist |
SyntaxError |
code or data cannot be parsed, as with JSON.parse() or new Function() |
URIError |
decodeURIComponent() and its relatives get a malformed address |
AggregateError |
several errors are reported at once, as by Promise.any() when every promise rejects |
EvalError |
no longer thrown by the language itself, though some browsers throw it when a security policy blocks eval() |
Firefox also has an InternalError, for example for too much recursion, but it is not part of the standard and other browsers throw a RangeError instead.
Custom error types and rethrowing
Section titled “Custom error types and rethrowing”A class that extends Error gives a program its own error types, which a catch block can recognise with instanceof. A catch should handle only the errors it understands and throw the rest again, so that an unexpected problem is not hidden.
class OutOfStockError extends Error { constructor(product, options) { super(`${product} is out of stock`, options); this.name = 'OutOfStockError'; this.product = product; }}
const stock = { kettle: 0, toaster: 3 };
const reserve = (product) => { if (!(product in stock)) { throw new Error(`Unknown product: ${product}`); } if (stock[product] === 0) { throw new OutOfStockError(product); } stock[product] -= 1; return `Reserved a ${product}`;};
try { for (const product of ['toaster', 'kettle', 'blender']) { try { console.log(reserve(product)); } catch (err) { if (err instanceof OutOfStockError) { console.log(`Sorry, the ${err.product} will be back soon`); } else { throw err; } } }} catch (err) { console.log(`Stopped: ${err.message}`);}This prints:
Reserved a toasterSorry, the kettle will be back soonStopped: Unknown product: blenderThe inner catch deals with the kettle and lets the unknown product’s error pass to the outer one, which ends the loop.
Keeping the original error
Section titled “Keeping the original error”When code catches a low-level error and throws a clearer one, the cause option keeps the original, so that nothing is lost for whoever investigates.
const loadProfile = (text) => { try { return JSON.parse(text); } catch (err) { throw new Error('Could not load the profile', { cause: err }); }};
try { loadProfile('not json');} catch (err) { console.log(err.message); console.log(err.cause.name, '-', err.cause.message);}This prints:
Could not load the profileSyntaxError - Unexpected token 'o', "not json" is not valid JSONfinally, and catch without a variable
Section titled “finally, and catch without a variable”The finally block runs whether or not an error was thrown, and even when try or catch returns, which makes it the place to tidy up, such as hiding a loading message. If catch does not need the error, the brackets after it can be left out.
const readFirst = (list) => { try { return list[0].toUpperCase(); } catch { return 'nothing'; } finally { console.log('finally runs before the value is returned'); }};
console.log(readFirst(['milk', 'eggs']));console.log(readFirst([]));This prints:
finally runs before the value is returnedMILKfinally runs before the value is returnednothingErrors in asynchronous code
Section titled “Errors in asynchronous code”A try block catches only errors thrown while it is running. A callback passed to setTimeout() or to an event listener runs later, after the try has finished, so it needs its own try inside. A promise that rejects does not throw at all until it is awaited, so put the await inside the try.
const fetchScore = async () => { throw new Error('Score service unavailable');};
try { const promise = fetchScore(); console.log('No error yet, only a rejected promise'); await promise; console.log('Not printed');} catch (err) { console.log('Caught with await:', err.message);}This prints:
No error yet, only a rejected promiseCaught with await: Score service unavailableWithout await, a promise chain handles the same error with .catch(). Async/Await covers this in more detail.
Steve Griffith covers this topic in his video JavaScript Try…Catch plus Throwing Errors and Exceptions.