Jump to content

Featured Replies

Posted

You are reading Part 21 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 3]

Introduction

Errors are inevitable in programming, and JavaScript provides robust mechanisms to handle them gracefully. The try, catch, finally, and throw statements allow developers to manage errors efficiently, ensuring better debugging and preventing application crashes.

Effective error handling in JavaScript enhances code stability and debugging efficiency. Using try, catch, finally, and throw, along with debugging tools, ensures that applications run smoothly even in the presence of errors. Mastering these techniques is essential for writing robust JavaScript applications.

1. The try-catch Block

The try block allows execution of code that might cause an error, while the catch block handles any errors that occur.

Syntax:

try {
    // Code that may throw an error
} catch (error) {
    // Handle the error
}

Example:

try {
    let result = undefinedVariable * 10; // This will throw an error
} catch (error) {
    console.error("An error occurred:", error.message);
}

2. Using finally

The finally block executes code regardless of whether an error occurs or not. It is useful for cleanup tasks.

Example:

try {
    console.log("Executing code...");
    throw new Error("Something went wrong");
} catch (error) {
    console.error("Error caught:", error.message);
} finally {
    console.log("Execution completed.");
}

Output:

Executing code...
Error caught: Something went wrong
Execution completed.

3. Throwing Custom Errors

The throw statement allows manual error generation with custom messages.

Example:

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

try {
    console.log(divide(10, 0));
} catch (error) {
    console.error("Caught an error:", error.message);
}

4. Debugging JavaScript Errors

JavaScript provides multiple debugging tools:

  • console.log() – Print values to track execution.

  • console.error() – Highlight errors in the console.

  • console.warn() – Display warnings.

  • Debugger Statement – Pauses execution for inspection.

Example:

function debugExample() {
    let value = 42;
    console.log("Value:", value);
    debugger; // Execution pauses here in Developer Tools
    return value * 2;
}

debugExample();

5. Handling Asynchronous Errors

When working with Promises or async/await, error handling should be done with .catch() or try-catch inside async functions.

Example: Handling Errors in Promises

fetch("https://invalid-api-url.com")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error("Fetch error:", error.message));

Example: Handling Errors in Async/Await

async function fetchData() {
    try {
        let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
        if (!response.ok) {
            throw new Error("Failed to fetch data");
        }
        let data = await response.json();
        console.log("User Data:", data);
    } catch (error) {
        console.error("Error:", error.message);
    }
}
fetchData();

6. When to Use try-catch

Scenario

Use try-catch?

Simple operations like variable assignments

No

Fetching API data

Yes

Reading from external files

Yes

Critical sections where failure must be handled

Yes

You are reading Part 21 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 3]

  • Views 39
  • Created
  • Last Reply

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.