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.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
<!DOCTYPE html><html><head></head><body><script>
try {
asdd(5);
} catch(err){
document.write(err.message);
} finally {
document.write(".");
}
document.write(" program not halted."); // asdd is not defined. program not halted.</script></body></html>
</script></body><html>RESETRUNFULL
<!DOCTYPE html><html><body><script>
<!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."); // Division by zero.</script></body></html>
</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.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
try {
var a = undefinedVariable;} catch (e) {
console.log(e instanceof ReferenceError); // true
console.log(e.message); // "undefinedVariable is not defined"
console.log(e.name); // "ReferenceError"
console.log(e.fileName); // "MyFile/1"
console.log(e.lineNumber); // 2
console.log(e.columnNumber); // 6
console.log(e.stack); // "@ MyFile/2:2:7\n"}
</script></body><html>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'));