Day 21 Error Handling — try/catch/finally
Real programs mein errors aate hain — network fail hota hai, user galat input deta hai, file nahi milti. try/catch se hum errors gracefully handle karte hain taake app crash na kare.
try / catch / finally
try mein risky code likhte hain. Agar error aaye to catch chalata hai. finally hamesha chalata hai — error ho ya na ho.
try {
let result = 10 / 0;
console.log(result); // Infinity — no error
let arr = null;
arr.length; // ❌ TypeError: Cannot read properties of null
} catch (error) {
console.log("Error caught:", error.message);
console.log("Error type:", error.name); // TypeError
} finally {
console.log("This always runs — cleanup karo yahan");
}
Custom Errors — throw
throw se khud error create kar sakte hain. Validation ke liye bahut useful hai.
function divide(a, b) {
if (typeof a !== "number" || typeof b !== "number") {
throw new TypeError("Both arguments must be numbers");
}
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // throws!
} catch (err) {
console.error("❌", err.message);
}
// Custom Error class
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
throw new ValidationError("Email invalid hai", "email");
Async Error Handling
async/await ke saath try/catch use karo async errors ke liye.
async function fetchData(url) {
try {
let res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
if (err instanceof TypeError) {
console.error("Network error — internet check karo");
} else {
console.error("API Error:", err.message);
}
return null; // graceful fallback
}
}
🎯 Practice Challenge
validateUser(user) function banao jo age < 0 par RangeError, missing name par ValidationError throw kare. try/catch se test karo.