Error Handling: try, catch, finally & throw
1. Simple Definition
Jab JavaScript code me koi unexpected problem (bug) aati hai, toh by-default poora program turant crash ho jata hai aur aage ka code execute hona band ho jata hai. Error Handling ka matlab hai try...catch blocks ka use karke us error ko catch (pakadna) karna, user ko clean error message dikhana, aur application ko crash hone se bachana!
2. Real-Life Analogy
• try: Normal road par drive karna (Risk wala code run karna).
• catch: Agar achanak collision/accident (Error) ho gaya, toh emergency airbag turant open ho kar passenger ko bacha leta hai (Crash hone se protect karta hai).
• finally: Chahe accident ho ya na ho, car ki battery aur lights aakhri me safely off hoti hain!
3. Why Do We Need It?
Network fail ho jana, user dwara invalid JSON upload karna, ya server ka 500 error aana common batein hain. Agar aap error handle nahi karenge, toh user ki screen blank white ho jayegi!
4. Syntax
try {
// Risky code jisme error aa sakta hai
const data = JSON.parse(userInput);
} catch (error) {
// Error aane par ye block execute hoga
console.error("Oops! Parsing me error aaya:", error.message);
} finally {
// Ye block 100% execute hoga (Chahe error aaye ya na aaye!)
hideLoadingSpinner();
}
5. Basic Example (Custom Error Throwing)
function withdrawMoney(balance, amount) {
try {
if (amount <= 0) {
throw new Error("Invalid withdrawal amount!");
}
if (amount > balance) {
throw new Error("Insufficient Balance! Aapke account me paise kam hain.");
}
const newBalance = balance - amount;
return `Naya Balance: ₹${newBalance}`;
} catch (err) {
return `Transaction Failed: ${err.message}`;
}
}
console.log(withdrawMoney(1000, 1500));
6. Output / Expected Result
7. Code Explanation: Common JS Error Types
| Error Type | Reason (Kyun Aata Hai?) | Example Code |
|---|---|---|
ReferenceError |
Aise variable ko use karna jo exist hi nahi karta ya declare nahi hua | console.log(unknownVar); |
TypeError |
Galat type par operation karna (jaise null par method call karna) | null.toUpperCase(); |
SyntaxError |
JavaScript rules todna (jaise bracket band na karna) | const x = ; |
RangeError |
Number limit se bahar jana | (10).toFixed(200); |
8. Real-World Example
API Data Fetching: Jab user offline hota hai ya Wi-Fi disconnect ho jata hai, try...catch se error catch karke screen par "Please check your internet connection" banner dikhaya jata hai.
9. Common Mistakes
try { ... } catch (e) { } — khali catch block likhna sabse dangerous mistake hai! Isse bugs chhupe rehte hain aur ghanto debugging me waste hote hain. Hamesha error log ya handle karein!
10. Best Practices
- Meaningful custom errors throw karein:
throw new Error("Password must have at least 8 characters");. - Resource cleanup (jaise loading spinners band karna, modal close karna) ke liye hamesha
finallyblock use karein.
11. Try It Yourself
Playground me JSON.parse("Invalid JSON string") ko try-catch me wrap karke error message print karein.
12. Challenge
Ek Safe Calculator function banayein jo agar 0 se divide kiya jaye (b === 0) toh throw new Error("Zero se divide nahi kar sakte!") throw kare.
13. Interview Questions
Answer: finally block hamesha try aur catch ke return statements ko override kar deta hai! Agar try me return 1 ho aur finally me return 2 ho, toh caller ko hamesha 2 milega.
14. Quick Revision
trytests risky code.catch(e)catches runtime exceptions.finallyalways executes.throw new Error(...)creates intentional checkpoints.
15. FAQ
Q1. Kya SyntaxError ko try-catch se pakad sakte hain?
Parsing stage par aane wale syntax errors ko try-catch nahi pakad sakta kyunki code execute hi nahi ho pata. Sirf runtime syntax errors (jaise JSON.parse() me) catch hote hain.
Q2. Error object ke do main properties kaunsi hoti hain?
err.name (e.g. "TypeError") aur err.message (description).
Q3. err.stack kya hota hai?
Stack trace jo exact file name aur line number batata hai jahan error generate hua.
Q4. Asynchronous code me try-catch kaise lagayein?
async/await ke sath try...catch perfectly work karta hai!
Q5. Custom error classes kaise banate hain?
class ValidationError extends Error { ... } se inheritance use karke.
Error Handling: try, catch, finally & throw
1. Simple Definition
Error Handling is the programming practice of gracefully anticipating, detecting, and resolving runtime anomalies without crashing the entire web application. JavaScript handles errors using try, catch, finally blocks, and custom error generation via throw new Error().
2. Real-Life Analogy
• try: A trapeze artist executing a complex airborne flip.
• catch: If they slip in mid-air, a soft safety net catches them safely before hitting the floor, preventing fatal injury.
• finally: Irrespective of whether the artist lands smoothly or falls into the net, the stage lights are always turned off at closing time!
3. The try / catch / finally Architecture
function parseUserData(rawJson) {
try {
console.log("Attempting to parse user JSON...");
const user = JSON.parse(rawJson); // Might throw SyntaxError
if (!user.email) {
throw new Error("Missing mandatory user email field!");
}
return user;
} catch (err) {
console.error("Caught an error gracefully:", err.name, err.message);
return null; // Safe fallback
} finally {
console.log("Cleanup complete. This line runs 100% of the time!");
}
}
4. Built-in JavaScript Error Types
| Error Type | Trigger Condition | Example |
|---|---|---|
ReferenceError |
Accessing an undeclared variable | console.log(notDefinedVar); |
TypeError |
Calling non-functions or accessing null/undefined | null.toUpperCase() |
SyntaxError |
Invalid code syntax or malformed JSON | JSON.parse("bad json") |
RangeError |
Number out of allowable range or infinite recursion | new Array(-1) |
5. Common Mistakes
Writing an empty catch block catch (e) {} swallows all errors silently! You will spend hours wondering why features fail silently in production. Always log the error or report it to your telemetry service!
6. Best Practices
- Always throw standard Error instances:
throw new Error("Reason"), never raw strings. - Use
finallyto release resources, clear timers, or close modal spinners. - Catch only specific errors you know how to handle gracefully.
7. Practice Exercise
Write a function safeGetStorage(key) that retrieves a value from localStorage, attempts to JSON.parse() it inside a try/catch block, and returns null if corrupt data throws an error.
8. Interview Questions
Answer: Yes! Even if the try or catch block executes a return statement, the finally block is guaranteed to execute immediately before the function actually returns control to the caller.
9. Summary / Cheat Card
trytests code for exceptions.catch (err)handles the failure without crashing the runtime.finallyalways runs regardless of outcome.- Use
throw new Error()for domain-specific validation.
10. FAQ
Q1. Can try/catch catch asynchronous errors inside setTimeout?
No! A synchronous try/catch block completes execution before the asynchronous callback runs. For asynchronous code, use async/await with try/catch or .catch() on Promises.