«Back to Home

Learn JavaScript

Topics

Error Handling with try, catch, finally

Errors are a normal part of programming.
Sometimes your code may run into unexpected issues, such as:

  • Invalid input

  • Network problems

  • Wrong variable names

  • Missing data

  • Incorrect calculations

If you don’t handle these errors properly, your entire program might stop working. This is why JavaScript provides a safe way to manage errors using:

  • try

  • catch

  • finally

Understanding error handling is important for college students and recent graduates because real-world applications often require stable, crash-resistant code.

Why Do We Need Error Handling?

Without try–catch:

  • One error can break the program

  • User experience becomes poor

  • Debugging becomes difficult

  • Application becomes unreliable

With try–catch:

  • The program continues running

  • Errors are handled safely

  • Users get meaningful messages

  • You can debug issues easily

Basic Structure of try–catch

try {
    // code that may have an error
} catch (error) {
    // code to handle the error
}

Example 1: Basic Error Handling

try {
    console.log(x); // x is not defined
} catch (error) {
    console.log("Something went wrong!");
}

Output:

Something went wrong!

The program does NOT crash—it continues safely.

The error Object (Very Useful)

The catch block receives an error object that contains detailed information.

try {
    console.log(student);
} catch (err) {
    console.log("Error:", err.message);
}

Output:

Error: student is not defined

This helps in debugging.

Example 2: Handling Wrong JSON

try {
    JSON.parse("{name: 'Aman'}"); // invalid JSON format
} catch (error) {
    console.log("Invalid JSON format");
}

Output:

Invalid JSON format

JSON errors are very common when working with APIs.

finally Block

The finally block always runs, whether there is an error or not.

Structure:

try {
    // risky code
} catch (error) {
    // error handling
} finally {
    // always runs
}

Example with finally

try {
    let a = 10 / 2;
    console.log(a);
} catch (err) {
    console.log("Error occurred");
} finally {
    console.log("Program finished");
}

Output:

5
Program finished

When finally Is Useful?

  • Closing database connections

  • Stopping loaders or spinners

  • Resetting UI states

  • Logging program completion

throw Keyword (Throwing Your Own Error)

Sometimes you want to create custom errors.

function checkAge(age) {
    if (age < 18) {
        throw new Error("You must be 18 or older");
    }
    return "Access granted";
}

try {
    console.log(checkAge(15));
} catch (err) {
    console.log(err.message);
}

Output:

You must be 18 or older

The throw keyword terminates the function and raises an error for the catch block to handle.

Real-Life Example: Form Validation

function validateName(name) {
    if (name === "") {
        throw new Error("Name cannot be empty");
    }
    return "Valid name";
}

try {
    console.log(validateName(""));
} catch (err) {
    console.log("Error:", err.message);
}

Output:

Error: Name cannot be empty

Real-Life Example: Prevent App Crashes

let data = null;

try {
    console.log(data.name); // null has no property 'name'
} catch (err) {
    console.log("Data is missing");
}

Output:

Data is missing

Preventing crashes is important for stable applications.

Example Program (Complete)

function divide(a, b) {
    if (b === 0) {
        throw new Error("Cannot divide by zero");
    }
    return a / b;
}

try {
    let result = divide(10, 0);
    console.log(result);
} catch (err) {
    console.log("Error:", err.message);
} finally {
    console.log("Operation complete");
}

Output:

Error: Cannot divide by zero
Operation complete

Common Mistakes Beginners Make

  1. Forgetting to wrap risky code inside try–catch

  2. Misusing throw without catch

  3. Writing too much code inside try block

  4. Ignoring error messages

  5. Assuming finally runs only after errors (it always runs)

Practice Tasks (Do It Yourself)

  1. Write a function that throws an error if age is less than 10.

  2. Create a try–catch to handle parsing invalid JSON.

  3. Use finally to print "Done!" at the end of a calculation.

  4. Throw a custom error if a number is negative.

  5. Write a login function that throws an error if username is empty.