⚠️ Exception Handling in JavaScript
Last Updated: 22nd October 2025
Exception Handling means detecting and handling runtime errors in your program without stopping its execution.
Hinglish Tip 🗣: Agar program me koi “galti” (error) ho jaaye, to JS usse handle kar sake bina crash hue — yehi exception handling ka kaam hai.
✏ Why We Need It?
- Prevents program from breaking suddenly.
- Helps to debug easily and show custom error messages.
- Keeps the app running smoothly even if an error occurs.
💡 The try...catch Statement
Basic structure for handling errors.
try {
// Code that may cause an error
let x = y + 5; // y is not defined → error
} catch (error) {
// Code to handle the error
console.log("Error Occurred:", error.message);
}
Hinglish Tip 🗣: try block me risky code likhte hain, aur catch block me batate hain agar kuch galat ho gaya to kya karna hai
finally Block
The finally block always executes, whether error happens or not.
try {
console.log("Running code...");
let a = 10 / 0; // valid, no error
} catch (error) {
console.log("Error:", error);
} finally {
console.log("Finally block always runs!");
}
Custom Errors
The throw Statement Used to create custom errors manually.
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed!");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (error) {
console.log("Custom Error:", error.message);
}
Hinglish Tip 🗣: throw ka matlab hai “error fenk do” jise catch pakad sake.
Error Object Properties
Every error object has a name, message, and stack property.
name: The name of the error (e.g., "SyntaxError"). message: A description of the error (e.g., "Unexpected token"). stack: A stack trace, which is a list of function calls leading up to the error (e.g., "at foo (/path/to/file.js:123:45)").
try {
nonExistent();
} catch (err) {
console.log(err.name); // ReferenceError
console.log(err.message); // nonExistent is not defined
}
Common Error Types
- SyntaxError
- ReferenceError
- TypeError
- RangeError
- Error
- EvalError