MENU
Error Handling
Catching an error prevents the execution from halting as a result of the error. Errors are caught within try{...} and handled in catch(e){...} (the (e) clause has become optional for catch.) The finally{...} clause will always be executed, even if there is no error.
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
try {
asdd(5);
} catch (err) {
document.write(err.message);
} finally {
document.write(".");
}
document.write(" program not halted.");
</script>
</body>
</html><!DOCTYPE html>
<html>
<head></head>
<body>
<script>
try {
var a = 0;
if (a == 0) throw "Division by zero.";
document.write(5 / a);
} catch (err) {
document.write(err);
}
throw "MyError"; // program halted here
document.write("program halted.");
</script>
</body>
</html>Seven Objects inherit from Error: EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError. The inherited properties are: .message, .name, .fileName, .lineNumber, .columnNumber, and .stack.
try {
var a = undefinedVariable;
} catch (e) {
console.log(e instanceof ReferenceError);
console.log(e.message);
console.log(e.name);
console.log(e.fileName);
console.log(e.lineNumber);
console.log(e.columnNumber);
console.log(e.stack);
}When an error is thrown in response to another (eg. inside a catch block, while handling a lower-level failure), ECMAScript 2022 lets you record that original error using the cause option, the second argument accepted by the Error constructor (and its subtypes): new Error(message, {cause}). The original error is then available as the new error's .cause property, giving a traceable chain instead of losing the root cause.
function loadConfig() {
try {
JSON.parse('{ bad json');
} catch (err) {
throw new Error('Could not load configuration.', {cause: err});
}
}
try {
loadConfig();
} catch (e) {
console.log(e.message);
console.log(e.cause.name);
}Error.isError(value), added in ECMAScript 2026, reliably tests whether value is an Error (of any built-in or custom subtype). Unlike 'value instanceof Error', it also correctly recognizes errors created in a different realm (eg. a different iframe or worker, which has its own separate Error constructor), where 'instanceof' would incorrectly return false.
console.log(Error.isError(new TypeError('x')));
console.log(Error.isError({message: 'x'})); // not really an Error
console.log(Error.isError('x'));