JavaScript
Catch unexpected mistakes gracefully with try, catch, finally, custom errors, and clean defensive programming.
Error Handling in Simple Terms
In JavaScript, an unhandled error is like an emergency brake: it stops your entire program immediately and crashes your app. Error Handling is how you catch problems gracefully, recover from them, and keep your application running smoothly for users.
Think of your code like driving a car:
try: You are driving down the road on a normal day.throw: An engine sensor detects smoke or flat tire and sounds a warning alarm.catch: The airbag and emergency brakes deploy safely so nobody gets hurt and the car doesn't total.finally: You turn off the ignition key and lock the doors—this happens whether you parked peacefully or had a blowout!
The Core try...catch...finally Blueprint
Use try to run code that might fail (like reading user input or parsing JSON), catch to handle the failure, and finally to run cleanup logic that must ALWAYS run.
function parseUserData(rawJson) {
try {
console.log("1. Reading incoming data...");
const user = JSON.parse(rawJson);
console.log("2. User parsed:", user.name);
return user;
} catch (error) {
console.warn("2. Caught an error:", error.name, "->", error.message);
return { name: "Guest User", role: "anonymous" };
} finally {
console.log("3. Cleanup complete (always executes).");
}
}
// Case A: Valid JSON
parseUserData('{"name": "Aman"}');
// Case B: Corrupted JSON (will not crash your app!)
parseUserData('{"invalid-json}');
1. Reading incoming data... 2. User parsed: Aman 3. Cleanup complete (always executes). 1. Reading incoming data... 2. Caught an error: SyntaxError -> Unexpected end of JSON input 3. Cleanup complete (always executes).
The throw Keyword & Built-in Errors
You can create and trigger your own custom error using throw new Error("message") whenever bad input or invalid business rules are detected.
ReferenceError
Occurs when referencing an undeclared variable (e.g. console.log(xyz)).
TypeError
Occurs when an operation is performed on an incompatible type (e.g. null.name or 123()).
SyntaxError
Occurs when the JavaScript engine encounters code that violates JS grammar (e.g. bad JSON).
RangeError
Occurs when a value is outside its allowed range (e.g. new Array(-5) or recursion overflow).
Creating Custom Error Classes
In modern production apps, you can extend the native Error class to categorize errors like network issues, validation errors, or auth failures.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function registerUser(age) {
if (typeof age !== "number") {
throw new TypeError("Age must be a number");
}
if (age < 18) {
throw new ValidationError("Must be 18 or older to register");
}
return "Registration approved!";
}
try {
registerUser(15);
} catch (err) {
if (err instanceof ValidationError) {
console.log("Validation issue:", err.message);
} else {
console.log("System error:", err.message);
}
}
Validation issue: Must be 18 or older to register
Hands-On Practice: Safe Bank Withdrawal
Complete the function safeWithdraw(balance, amount). If amount > balance, throw an Error("Insufficient funds"). Otherwise, return the remaining balance.