35 Mins intermediate
13. Error Handling
Architecture
Error Handling
In production, APIs fail, networks drop, and users input bad data. A crashed app is a terrible user experience. Error handling allows you to catch these disasters gracefully.
🛡️ Try, Catch, Finally
You wrap dangerous code inside a try block. If it explodes, execution instantly jumps to the catch block without crashing the whole application.
try {
// Attempting to call a function that doesn't exist
fakeFunction();
console.log("This line will never run.");
} catch (error) {
// This intercepts the crash
console.error("Caught an error!", error.message);
} finally {
// This ALWAYS runs, crash or no crash. Used for cleanup.
console.log("Execution complete.");
}
OutputCaught an error! fakeFunction is not defined
Execution complete.
Execution complete.
⚡ Throwing Custom Errors
You can enforce business logic by manually triggering errors using the throw keyword.
function processPayment(amount) {
if (amount <= 0) {
throw new Error("Payment amount must be greater than zero.");
}
return `Processed $${amount}`;
}
try {
console.log(processPayment(-5));
} catch (err) {
console.error("Transaction Failed:", err.message);
}
OutputTransaction Failed: Payment amount must be greater than zero.
Knowledge Check
Ready to test your understanding of 13. Error Handling?