Know Your Enemy
When an error occurs, JavaScript creates an error object and passes it to the catch block. This object contains detailed information about what went wrong.
Key Properties
| Property | Description |
|---|---|
name | The error type (e.g., ReferenceError, SyntaxError, TypeError) |
message | A human-readable description of the error |
stack | The full call stack trace — which function called which |
try {
const data = JSON.parse('{ invalid json }');
} catch (err) {
console.log(err.name); // SyntaxError
console.log(err.message); // Unexpected token i in JSON...
console.log(err.stack); // Full stack trace
}
Throwing Your Own Errors
function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero is not allowed!');
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (err) {
console.log('Caught: ' + err.message);
}
Important
You can throw any value (throw 42, throw "oops"), but always use new Error("message") — it preserves the stack trace which is essential for debugging.