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.

💡 Real-World Analogy: The Car Safety System

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}');
Output
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.

01

ReferenceError

Occurs when referencing an undeclared variable (e.g. console.log(xyz)).

02

TypeError

Occurs when an operation is performed on an incompatible type (e.g. null.name or 123()).

03

SyntaxError

Occurs when the JavaScript engine encounters code that violates JS grammar (e.g. bad JSON).

04

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);
    }
}
Output
Validation issue: Must be 18 or older to register
🎯 Error Handling Interview Deck
Question 1 of 5
JavaScript Interview PuzzleQ1 of 5
function test() {
    try {
        return 10;
    } finally {
        console.log("Inside Finally");
    }
}
const res = test();
console.log("Returned:", res);
What will be logged to the console?
JavaScript Interview PuzzleQ2 of 5
try {
    console.log("Before throw");
    throw new Error("Bad Input");
    console.log("After throw");
} catch (err) {
    console.log("Caught:", err.message);
}
What will be logged to the console?
JavaScript Interview PuzzleQ3 of 5
try {
    const num = 42;
    num.toUpperCase();
} catch (err) {
    console.log(err.name);
}
What error name is captured in the catch block?
JavaScript Interview PuzzleQ4 of 5
function checkOverride() {
    try {
        return 1;
    } finally {
        return 2;
    }
}
console.log(checkOverride());
What is returned by checkOverride()?
JavaScript Interview PuzzleQ5 of 5
try {
    setTimeout(() => {
        throw new Error("Timer Boom!");
    }, 100);
} catch (err) {
    console.log("Caught:", err.message);
}
What happens when this code runs?

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.