Skip to main content
JavaScript Basics
CHAPTER 26 Beginner

JavaScript Error Handling

Updated: May 12, 2026
15 min read

# JavaScript Error Handling

No matter how good a programmer you are, your code will encounter errors. A server will go offline, a user will type a letter where a number should be, or you will accidentally misspell a variable name.

If JavaScript hits an error it doesn't know how to handle, it completely crashes and stops executing the rest of the script. This chapter teaches you how to catch those errors gracefully so your app stays alive.

1. Introduction

Error handling in JavaScript revolves around the try...catch statement.

The concept is simple: you tell JavaScript to try running a block of code. If an error occurs, instead of crashing the browser tab, JavaScript immediately jumps into the catch block, allowing you to handle the problem (like showing an error message to the user) and continue running the rest of your app.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Use the try...catch statement to prevent app crashes.
  • Read and understand the Error object.
  • Use the finally block for cleanup operations.
  • Create custom errors using the throw keyword.
  • Build a Safe JSON Parser mini-project.

3. The try...catch Syntax

javascript
123456
// Syntax
try {
    // Code that might cause an error
} catch (error) {
    // Code to run IF an error occurs
}

---

4. Real-world Examples & Code Snippets

Example 1: A Standard Crash

javascript
12345678
// Example JavaScript
console.log("App Started...");

// We are calling a function that doesn't exist!
doSomethingAwesome(); 

// This line NEVER runs because the app crashed on the line above.
console.log("App Finished."); 

Example 2: Catching the Crash

javascript
1234567891011
// Example JavaScript
console.log("App Started...");

try {
    doSomethingAwesome(); // This will fail
} catch (error) {
    console.log("Whoops, we caught an error! Moving on...");
}

// This line WILL run now!
console.log("App Finished."); 

Example 3: The Error Object

The catch block automatically receives an object (usually named err or error) containing details about what went wrong. The most important property is error.message.

javascript
1234567
// Example JavaScript
try {
    let user = userProfileName; // userProfileName is not defined
} catch (error) {
    console.log("Error Name: " + error.name);       // Output: ReferenceError
    console.log("Error Msg:  " + error.message);    // Output: userProfileName is not defined
}

Example 4: The finally Block

The finally block is optional. It executes code AFTER try and catch, regardless of whether an error occurred or not. It is perfect for cleanup tasks, like hiding a "Loading" spinner.

javascript
1234567891011121314
// Example JavaScript
document.getElementById("loader").style.display = "block";

try {
    // Simulate fetching data
    console.log("Fetching data...");
    // fakeFetch(); // Uncomment to trigger error
} catch (error) {
    console.log("Failed to fetch.");
} finally {
    // This runs no matter what!
    document.getElementById("loader").style.display = "none";
    console.log("Cleanup complete.");
}

Example 5: Custom Errors (throw)

Sometimes, JavaScript's built-in syntax rules are fine, but your *business rules* are broken. You can force an error using the throw keyword.

javascript
1234567891011121314
// Example JavaScript
function checkAge(age) {
    try {
        if (age < 18) {
            // We manually trigger an error
            throw new Error("User must be 18 or older!"); 
        }
        console.log("Access Granted");
    } catch (error) {
        console.log("Access Denied: " + error.message);
    }
}

checkAge(15); // Output: Access Denied: User must be 18 or older!

Example 6: Handling JSON Parsing Errors

JSON.parse() is notoriously dangerous. If the server sends corrupted JSON text, JSON.parse throws a SyntaxError and crashes your app. ALWAYS wrap it in try...catch.

javascript
123456789
// Example JavaScript
const rawServerText = &#039;{ "id": 1, "name": "Alice"&#039;; // Missing closing brace!

try {
    const data = JSON.parse(rawServerText);
    console.log(data);
} catch (error) {
    console.error("The server sent invalid JSON data!", error.message);
}

Example 7: Handling fetch API Errors

When making web requests, use try...catch inside an async function (which we will learn in Chapter 28), or rely on .catch() for Promises.

javascript
1234567
// Example JavaScript (Promise approach)
fetch("https://invalid-url.com")
    .then(res => res.json())
    .catch(error => {
        // Fetch failed (network error)
        console.error("Network Error: Could not reach the server.");
    });

---

5. Common Mistakes for Beginners

  1. 1. Overusing try...catch: Do not wrap your entire JS file in one massive try...catch. Only wrap specific blocks of code that are inherently unpredictable (like JSON parsing, third-party API calls, or complex user inputs).
  1. 2. Ignoring the Catch Block: catch(e) { } with nothing inside is called "swallowing an error." The code fails silently, and you will have a nightmare trying to debug why your app isn't working. Always at least console.error(e).
  1. 3. Syntax Errors vs Runtime Errors: try...catch only catches Runtime errors (errors that happen while the code is running). It cannot catch Syntax errors (like forgetting a closing bracket } in your script), because the browser refuses to run the script at all.

6. Best Practices

  • Always validate inputs BEFORE trying to use them, rather than relying solely on try...catch to catch bad inputs.
  • Use throw new Error("msg") rather than just throw "msg". Throwing a proper Error object provides a Stack Trace, which helps you debug exactly which line caused the error.

7. Mini Project: Safe JSON Parser

Let's build a UI that allows a user to paste JSON data and tries to format it. If the user pastes bad data, we catch the crash and show a friendly error on the screen.

HTML:

html
1234567891011121314151617181920212223242526
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: sans-serif; padding: 20px; }
        textarea { width: 100%; height: 150px; font-family: monospace; padding: 10px; box-sizing: border-box; border: 2px solid #ccc; border-radius: 5px;}
        button { background: #333; color: white; padding: 10px 20px; border: none; cursor: pointer; margin-top: 10px; border-radius: 4px;}
        .output-box { margin-top: 20px; padding: 15px; border-radius: 5px; font-family: monospace; white-space: pre-wrap; background: #f8f9fa;}
        .error { border-left: 5px solid #dc3545; color: #dc3545; }
        .success { border-left: 5px solid #28a745; color: #28a745; }
    </style>
</head>
<body>

    <h2>Safe JSON Validator</h2>
    <textarea id="jsonInput" placeholder="Paste JSON here..."></textarea>
    <br>
    <button onclick="validateJSON()">Validate JSON</button>

    <div id="output" class="output-box">Waiting for input...</div>

    <script src="error.js"></script>
</body>
</html>

error.js:

javascript
1234567891011121314151617181920212223242526
// Example JavaScript
function validateJSON() {
    const rawInput = document.getElementById("jsonInput").value;
    const outputDiv = document.getElementById("output");

    if (rawInput.trim() === "") {
        outputDiv.innerHTML = "Please enter some JSON.";
        outputDiv.className = "output-box";
        return;
    }

    try {
        // 1. Attempt the dangerous operation
        const parsedObject = JSON.parse(rawInput);
        
        // 2. If it succeeds, format it nicely
        const prettyJSON = JSON.stringify(parsedObject, null, 4);
        outputDiv.innerHTML = "Valid JSON!\n\n" + prettyJSON;
        outputDiv.className = "output-box success";
        
    } catch (err) {
        // 3. Catch the crash!
        outputDiv.innerHTML = "<strong>Invalid JSON format!</strong>\n" + err.message;
        outputDiv.className = "output-box error";
    }
}

8. Exercises

  1. 1. Write a function divide(a, b) that throws a custom Error if b is 0.
  1. 2. Wrap a call to your divide(10, 0) function inside a try...catch block and console.log the error message.
  1. 3. Add a finally block that logs "Calculation attempted".

9. MCQs (Multiple Choice Questions)

Q1: What happens if JavaScript hits a runtime error without a try...catch block? A) It alerts the user. B) It skips the line and continues. C) The script execution halts completely. D) It converts the error to a string. *Answer: C*

Q2: Which block always runs regardless of whether an error occurred? A) catch B) try C) throw D) finally *Answer: D*

Q3: Which keyword allows you to manually generate an error? A) error B) throw C) catch D) reject *Answer: B*

10. Interview Questions

Q: What is a Stack Trace in JavaScript errors? *A: When you generate a new Error object, it contains a property called .stack. This is a string that shows exactly the sequence of function calls that led to the error, and the exact line number where the error occurred. It is invaluable for debugging.*

11. FAQs

Q: Why doesn't try...catch work on setTimeout? *A: try...catch is synchronous. If you put a setTimeout inside a try, the try block finishes instantly before the timeout triggers. When the timeout finally runs 2 seconds later and causes an error, it is no longer inside the try block. You must put the try...catch INSIDE the timeout callback.*

12. Summary

  • try allows you to test a block of code.
  • catch allows you to handle the error if the try block crashes.
  • finally allows you to run cleanup code regardless of success or failure.
  • throw new Error("msg") lets you create custom business-logic errors.
  • Never parse JSON without wrapping it in try...catch.

13. Next Chapter Recommendation

We just mentioned setTimeout. Dealing with time is a huge part of JavaScript. In the next chapter, JavaScript Timers and Intervals, we will learn how to delay execution, repeat functions, and build stopwatches.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·