Error Handling (try, catch, finally, throw)
Even the best code encounters unexpected errors—network timeouts, missing API keys, or invalid JSON. Robust error handling keeps your app from crashing.
What is it?
The `try...catch...finally` statement marks a block of statements to try, and specifies a response should an exception be thrown (`throw new Error(...)`).
Why is it used?
Gracefully recovers from failures, displays helpful error messages to users, and logs telemetry diagnostics.
Detailed Explanation
Structure:
• `try`: Contains code that might fail.
• `catch (err)`: Executes if an error occurs. The `err` object contains `.message`, `.name`, and `.stack`.
• `finally`: Executes unconditionally after try and catch have finished, ideal for closing modal loading spinners.
• `throw new Error('Custom message')`: Manually triggers an exception.
Syntax Structure
Syntax Blueprint
try {
// Code that may fail
throw new Error('Something went wrong');
} catch (error) {
console.error(error.message);
} finally {
// Always runs
}
Code Example
JAVASCRIPT Code
// Safe JSON Parser with Fallback
function safeJsonParse(jsonString, fallbackValue = {}) {
try {
return JSON.parse(jsonString);
} catch (err) {
console.warn("JSON parsing error intercepted:", err.message);
return fallbackValue; // Safe graceful fallback instead of crashing
} finally {
console.log("Parse operation attempted.");
}
}
// Testing with valid JSON
const validData = safeJsonParse('{"course":"Python","enrolled":true}');
console.log("Valid:", validData.course);
// Testing with corrupted/broken JSON
const corruptedData = safeJsonParse('{ broken-json: true }', { error: true });
console.log("Fallback recovered:", corruptedData);
Explanation of the Code
• Catches parsing exceptions without terminating application execution.
• Returns safe fallback object if input is corrupted.
• `finally` block logs telemetry.
Expected Output
Parse operation attempted.
Valid: Python
JSON parsing error intercepted: Unexpected token 'b' ...
Parse operation attempted.
Fallback recovered: { error: true }
Real-World Application
Used across payment gateways and authentication handlers to prevent UI crashes when third-party servers go down.
Common Mistakes to Avoid
• Leaving `catch` blocks completely empty (silent failures make debugging impossible!).
• Catching errors and ignoring them without alerting the user or logging the error.
Quick Practice Challenge
Write a function `divide(a, b)` that throws an Error if `b === 0` and catch it with `try...catch`.
Key Takeaways
• Wrap risky operations (JSON parsing, Fetch calls) in `try...catch`.
• Use `throw new Error()` for meaningful business rule validations.
• The `finally` block always executes for resource cleanup.