Error Handling in JavaScript

Error handling in JavaScript is like a safety net in a circus.
Your code walks the rope of logic — error handling prevents the entire system from collapsing when something unexpected happens.

Without error handling:

  • Applications crash
  • Users see blank pages
  • APIs fail silently
  • Debugging becomes painful

With proper error handling:

  • Applications become stable
  • Bugs become easier to track
  • User experience improves
  • Systems become production-ready

1. What is an Error in JavaScript?

An error is a problem that stops the normal execution of a program.

Example:

console.log(userName);

Output:

ReferenceError: userName is not defined

Because userName variable does not exist.


2. Why Error Handling is Important

Imagine:

  • Banking app transferring money
  • Login system authenticating users
  • Payment gateway processing transactions

One small error can break the workflow.

Error handling helps to:

  • Detect problems
  • Prevent crashes
  • Show meaningful messages
  • Recover gracefully

3. Types of Errors in JavaScript


A) Syntax Error

Occurs when code grammar is incorrect.

Example:

if (true {
    console.log("Hello");
}

Output:

SyntaxError: Unexpected token {

Because parenthesis is missing.


B) Reference Error

Occurs when accessing undeclared variables.

Example:

console.log(age);

Output:

ReferenceError: age is not defined

C) Type Error

Occurs when performing invalid operations on data types.

Example:

let num = 10;

num.toUpperCase();

Output:

TypeError: num.toUpperCase is not a function

Because numbers do not have toUpperCase().


D) Range Error

Occurs when value exceeds allowed range.

Example:

let arr = new Array(-1);

Output:

RangeError: Invalid array length

E) Logical Error

Program runs but gives wrong output.

Example:

let total = 10 + "5";

console.log(total);

Output:

105

No crash — but wrong logic.

These are the most dangerous errors.


4. try...catch Statement

Main mechanism for handling errors.


Syntax

try {
    // risky code
}
catch(error) {
    // handle error
}

Example

try {
    console.log(userName);
}
catch(error) {
    console.log("Something went wrong");
}

Output:

Something went wrong

Instead of crashing the application.


5. Understanding the Flow


Step-by-Step Logic

try {
    let result = 10 / 0;
}
catch(error) {
    console.log(error);
}

Flow:

  1. JavaScript enters try
  2. Executes risky code
  3. If error occurs:
    • execution stops inside try
    • control jumps to catch
  4. Error object is stored in parameter

6. The Error Object

The catch(error) parameter contains useful information.


Example

try {
    console.log(data);
}
catch(error) {
    console.log(error.name);
    console.log(error.message);
}

Output:

ReferenceError
data is not defined

Important Properties

Property Meaning
name Type of error
message Error description
stack Error trace

7. finally Block

finally always runs whether error happens or not.


Syntax

try {

}
catch(error) {

}
finally {

}

Example

try {
    console.log("Start");
}
catch(error) {
    console.log(error);
}
finally {
    console.log("Always runs");
}

Output:

Start
Always runs

Real-Life Use

Used for:

  • Closing database connections
  • Stopping loaders
  • Cleaning resources
  • Logging

8. throw Statement

Used to create custom errors.


Syntax

throw error;

Example

let age = 15;

try {
    if(age < 18) {
        throw "You are underage";
    }

    console.log("Access granted");
}
catch(error) {
    console.log(error);
}

Output:

You are underage

9. Throwing Custom Error Objects

Professional approach.


Example

try {
    let password = "123";

    if(password.length < 6) {
        throw new Error("Password too short");
    }
}
catch(error) {
    console.log(error.message);
}

Output:

Password too short

10. Nested try...catch

Possible to place try...catch inside another.


Example

try {

    try {
        console.log(user);
    }
    catch(error) {
        console.log("Inner error handled");
    }

}
catch(error) {
    console.log("Outer error handled");
}

Output:

Inner error handled

11. Error Handling in Functions


Example

function divide(a, b) {

    try {

        if(b === 0) {
            throw new Error("Cannot divide by zero");
        }

        return a / b;

    }
    catch(error) {
        return error.message;
    }

}

console.log(divide(10, 0));

Output:

Cannot divide by zero

12. Error Handling in JSON

Very common in APIs.


Example

let data = '{"name":"Anas"}';

try {

    let result = JSON.parse(data);

    console.log(result.name);

}
catch(error) {
    console.log("Invalid JSON");
}

Invalid JSON Example

let data = '{"name":"Anas"';

JSON.parse(data);

Output:

SyntaxError

13. Asynchronous Error Handling

Very important in modern JavaScript.


A) Promise Error Handling


Example

fetch("wrong-url")

.then(response => response.json())

.catch(error => {
    console.log("Fetch failed");
});

.catch() handles promise errors.


B) async/await Error Handling


Example

async function getData() {

    try {

        let response = await fetch("wrong-url");

        let data = await response.json();

        console.log(data);

    }
    catch(error) {
        console.log("Error fetching data");
    }

}

getData();

14. Real-World Form Validation Example


Example

function validateForm(username) {

    try {

        if(username === "") {
            throw new Error("Username required");
        }

        console.log("Form submitted");

    }
    catch(error) {
        console.log(error.message);
    }

}

validateForm("");

Output:

Username required

15. Best Practices for Error Handling


1. Never Ignore Errors

Bad:

catch(error) {

}

This hides bugs.


2. Show Meaningful Messages

Bad:

Error

Good:

"Invalid email format"

3. Use Custom Errors

Makes debugging easier.


4. Handle Async Errors Properly

Always use:

  • .catch()
  • try...catch with async/await

5. Avoid Overusing try...catch

Use it only around risky code.

Bad:

try {
    let x = 5;
}
catch(error) {

}

No need here.


16. Common Beginner Mistakes


Mistake 1

Using try...catch for syntax errors.

try {
    if(true {
}
catch(error) {
}

Syntax errors occur before execution.


Mistake 2

Forgetting await

try {
    fetch(url);
}
catch(error) {

}

This may not catch async errors.


Mistake 3

Throwing plain strings

Bad:

throw "Error";

Better:

throw new Error("Error");

17. Advanced: Custom Error Classes

Used in large applications.


Example

class ValidationError extends Error {

    constructor(message) {
        super(message);
        this.name = "ValidationError";
    }

}

try {

    throw new ValidationError("Invalid input");

}
catch(error) {

    console.log(error.name);
    console.log(error.message);

}

Output:

ValidationError
Invalid input

18. Difference Between Compile-Time and Runtime Errors

Type Meaning
Compile/Syntax Error Code cannot start
Runtime Error Error during execution

19. Practical Mini Project Example


ATM Withdrawal System

function withdraw(balance, amount) {

    try {

        if(amount > balance) {
            throw new Error("Insufficient balance");
        }

        if(amount <= 0) {
            throw new Error("Invalid amount");
        }

        balance -= amount;

        console.log("Remaining Balance:", balance);

    }
    catch(error) {
        console.log(error.message);
    }

}

withdraw(5000, 7000);

Output:

Insufficient balance

20. Visual Flow of Error Handling

START
   ↓
try block executes
   ↓
Error occurs?
   ↓
YES --------→ catch block runs
   ↓
NO
   ↓
finally block runs
   ↓
END

21. Summary Table

Concept Purpose
try Contains risky code
catch Handles errors
finally Always executes
throw Creates custom error
Error object Stores error details
async catch Handles async failures

Final Thought

A beginner writes code that works.
A professional writes code that survives failure.

Error handling is not merely about fixing bugs —
it is about building resilient systems that continue standing when storms arrive.

In modern software engineering, graceful failure is a mark of mature architecture.

List of Modules