Chapter XXIII · Error Handling
catch
The `catch` statement defines a code block to handle errors thrown by the preceding `try` block.
01 How It Works
Think of a safety net catching a gymnast and providing a cushion floor.
The `catch` clause receives an error object containing details like message, name, and stack trace for debugging.
example.js
try {
nonExistentFunction();
} catch (error) {
console.log("Caught error:", error.message);
}
1. Intercept an exception thrown from a `try` block.
2. Receive error object parameters inside catch.
3. Run fallback recovery logic or logging.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
try {
throw new TypeError("Invalid type assignment");
} catch (err) {
console.warn(err.name, err.message);
}
Key Takeaway
Use `catch` blocks to gracefully process and recover from runtime errors.