The Traditional Throw/Try-Catch Pattern
What You'll Learn
You'll understand how JavaScript uses throw and try-catch blocks to handle errors and control program flow when things go wrong.
What Is the Throw/Try-Catch Pattern?
In JavaScript, when something unexpected happens—like dividing by zero, accessing a property on undefined, or a network request failing—the language throws an error. Instead of letting your entire program crash, you can catch these errors and decide how to handle them.
Think of it like a safety net at a circus: the trapeze artist (your code) might fall (throw an error), but the net (try-catch) catches them so the show can continue gracefully.
How It Works
Try block: Wrap risky code that might fail:
try {
const data = JSON.parse(corruptedString);
processData(data);
} catch (error) {
console.error("Failed to parse JSON:", error.message);
}
Catch block: Handles the error if one is thrown. The error object contains details about what went wrong.
Throw statement: You can explicitly throw your own errors:
function withdraw(amount) {
if (amount > balance) {
throw new Error("Insufficient funds");
}
balance -= amount;
}
Finally block (optional): Runs cleanup code whether an error occurred or not:
try {
openConnection();
} catch (err) {
logError(err);
} finally {
closeConnection(); // Always runs
}
When to Use This Pattern
Use try-catch for operations that might fail unpredictably: parsing user input, file operations, API calls, or when you explicitly throw errors to signal invalid states. Don't overuse it—checking conditions with if statements is often clearer.
Key Takeaway: The throw/try-catch pattern lets you anticipate and gracefully handle errors, preventing crashes and giving you control over failure scenarios.