- If an exception happens in “scheduled” code, like in setTimeout, then try..catch won’t catch it.
- That’s because try..catch actually wraps the setTimeout call that schedules the function.
- But the function itself is executed later, when the engine has already left the try..catch construct.
- To catch an exception inside a scheduled function, try..catch must be inside that function.
setTimeout(function() {
try {
noSuchVariable; // try..catch handles the error!
} catch (error) {
console.log(error);
} finally {
// Execute always ...
}
}, 1000);
- The try..finally construct, without catch clause, is also useful.
- We apply it when we don’t want to handle errors right here, but want to be sure that processes that we started are finalized.
Error Object
- When an error occurs, JavaScript generates an object containing the details about it.
- For all built-in errors, the error object inside
catch
block has two main properties:
name
: error name.
- For an undefined variable that’s
"ReferenceError"
.
message
: textual message about error details.
- There are other non-standard properties available in most environments.
- One of most widely used and supported is
stack
.
Throwing Custom Errors
- The throw operator generates an error.
- Technically, we can use anything as an error object.
- That may be even a primitive, like a number or a string.
- It’s better to use objects, preferably with
name
and message
properties.
- JavaScript has many built-in constructors for standard errors:
Error
, SyntaxError
, ReferenceError
, TypeError
and others.
let error = new Error(message);
let error = new SyntaxError(message);
let error = new ReferenceError(message);
throw error;
throw new Error(message);
- For built-in errors (not for any objects, just for errors), the name property is exactly the name of the constructor.
- Message is taken from the argument.
Extending Error
class Error {
constructor(message) {
this.message = message;
// (different names for different built-in error classes)
this.name = "Error";
}
}
class ValidationError extends Error {
constructor(message) {
super(message); // (1)
this.name = "ValidationError";
}
}