Skip to main content

Command Palette

Search for a command to run...

Error handling mechanism : try-catch-finally

Updated
•4 min read•View as Markdown
Error handling mechanism : try-catch-finally

1. What Are Errors in JavaScript?

Errors are problems that occur when your JavaScript code runs. They stop your program from working as expected.

There are mainly three types of errors:

a) Syntax Errors

These happen when your code breaks JavaScript rules.

Example:

console.log("Hello"

Missing closing bracket → code won’t run at all.

b) Runtime Errors

These happen while the code is running.

Example:

let user = null; 

console.log(user.name);

Here, you are trying to access name from null.

c) Logical Errors

The code runs, but the output is wrong.

Example:

let total = 10 + "5";  // "105" instead of 15

2. Why Error Handling Matters ?

Without error handling:

  • Your app can crash

  • Users get a bad experience

  • Debugging becomes difficult.

With error handling:

  • You can control failures

  • Show meaningful messages

  • Keep the app running smoothly.

This is called graceful failure — your app doesn’t break completely even if something goes wrong.


3. Using try...catch

JavaScript gives us a way to handle runtime errors using try...catch.

Basic Syntax:

 try { 
   // code that may cause error 
} catch (error) { 
  // code to handle error 
}

Example

try {
    let data = JSON.parse("invalid json");
} catch (error) {
    console.log("Something went wrong");
}

Here:

  • try runs the risky code

  • If error occurs → catch runs


4. Understanding the Error Object

Inside catch, you get an error object.

Example:

try {
    let x = y;
} catch (error) {
    console.log(error.name);    // ReferenceError
    console.log(error.message); // y is not defined
}

This helps in debugging.


5. The finally Block

finally always runs — whether error happens or not.

Syntax

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

Example

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

Use cases:

  • Closing files

  • Stopping loaders

  • Cleaning resources


6. Throwing Custom Errors

You can create your own errors using throw.

Example

function withdraw(amount) {
    if (amount > 1000) {
        throw new Error("Limit exceeded");
    }
    return "Success";
}

Using it:

try {
    withdraw(2000);
} catch (error) {
    console.log(error.message);
}

7. Types of Built-in Errors

JavaScript provides different error types:

  • Error (generic)

  • ReferenceError

  • TypeError

  • SyntaxError

  • RangeError

Example:

let num = null;
num.toUpperCase(); // TypeError

8. Error Handling Flow

Execution works like this:

Step 1: Try block runs
Step 2: If no error → skip catch → run finally
Step 3: If error → jump to catch → then run finally

9. Nested try...catch

You can use try...catch inside another try block.

try {
    try {
        throw new Error("Inner error");
    } catch (inner) {
        console.log("Handled inside");
    }
} catch (outer) {
    console.log("Handled outside");
}

10. Async Error Handling

Errors in async code behave differently.

Using async/await

async function fetchData() {
    try {
        let res = await fetch("wrong-url");
    } catch (error) {
        console.log("Failed to fetch");
    }
}

Without try...catch (Promises)

fetch("wrong-url")
    .then(res => res.json())
    .catch(error => console.log("Error occurred"));

11. Best Practices

  • Don’t overuse try...catch

  • Catch only meaningful errors

  • Always log errors while debugging

  • Use custom error messages

  • Avoid empty catch blocks

Bad:

try {
    riskyCode();
} catch (e) {}

Good:

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

12. Real-World Example

function login(user) {
    try {
        if (!user) {
            throw new Error("User not found");
        }

        console.log("Login successful");
    } catch (error) {
        console.log("Login failed:", error.message);
    } finally {
        console.log("Process finished");
    }
}

13. Debugging Benefits

Error handling helps you:

  • Identify exact issue location

  • Understand error type

  • Fix bugs faster

  • Improve code quality


Final Thoughts

Error handling is not just about fixing bugs — it’s about writing reliable and user-friendly applications.

Start with:

  • Understanding errors

  • Using try...catch properly

Then move to:

  • Custom errors

  • Async handling

  • Clean debugging practices

Mastering this will make your JavaScript code much more professional and robust.

Thank you for taking the time to read this blog. I hope it helped you understand JavaScript error handling in a clear and simple way.
I’m always open to feedback and suggestions, so feel free to share your thoughts or improvements.

2 views