Dive Deep into JavaScript Error Handling CODE EXERCISE 

Dive Deep into JavaScript Error Handling

CODING EXERCISES TEST YOUR SKILLS

🚀 Dive Deep into JavaScript Error Handling! 🚀

10 comprehensive JavaScript exercises focused on mastering error handling. These exercises are designed to strengthen your skills in managing and responding to exceptions in code, a critical skill for any robust application. 💡💻

From basic try-catch blocks to advanced handling in asynchronous operations, these exercises cover a wide range of real-world scenarios. 🌐🔧

What’s Included:

  • Basic and Advanced Try-Catch Usage
  • Implementing Finally for Cleanup
  • Creating and Using Custom Error Types
  • Error Propagation Techniques
  • Asynchronous Error Handling with Async/Await
  • Rethrowing Errors for Multi-level Handling
  • Handling Multiple Error Types
  • Understanding Error-First Callbacks

These exercises are perfect for both beginners who are just getting started and seasoned developers looking to brush up on their error handling strategies. 🎓👨‍💻👩‍💻

Exercise 1: Basic Try-Catch Usage

Problem Statement:

Create a function that divides two numbers and uses a try-catch block to handle any division by zero errors.

Hint/Explanation:

The try-catch block is used to handle exceptions. If an error occurs in the try block, it is caught in the catch block.

Solution:

function divide(a, b) {

    try {

        if (b === 0) {

            throw new Error(“Cannot divide by zero”);

        }

        return a / b;

    } catch (error) {

        console.error(error.message);

        return null;

    }

}

console.log(divide(10, 2));  // 5

console.log(divide(10, 0));  // Error: Cannot divide by zero

Exercise 2: Using the Finally Block

Problem Statement:

Modify the previous function to include a finally block that logs a message regardless of whether an error occurred.

Hint/Explanation:

The finally block is executed after the try and catch blocks, regardless of the result.

Solution:

function divideWithFinally(a, b) {

    try {

        if (b === 0) {

            throw new Error(“Cannot divide by zero”);

        }

        return a / b;

    } catch (error) {

        console.error(error.message);

        return null;

    } finally {

        console.log(“Division operation completed”);

    }

}

divideWithFinally(10, 0); // Error: Cannot divide by zero, followed by “Division operation completed”

Exercise 3: Custom Error Types

Problem Statement:

Create a custom error type InvalidInputError and use it in a function that validates user input.

Hint/Explanation:

Custom error types can extend the Error class to provide more specific error information.

Solution:

class InvalidInputError extends Error {

    constructor(message) {

        super(message);

        this.name = “InvalidInputError”;

    }

}

function validateInput(input) {

    try {

        if (typeof input !== ‘string’) {

            throw new InvalidInputError(“Input must be a string”);

        }

        return “Valid input”;

    } catch (error) {

        console.error(`${error.name}: ${error.message}`);

        return null;

    }

}

console.log(validateInput(123)); // InvalidInputError: Input must be a string

Exercise 4: Error Propagation

Problem Statement:

Write a function that calls another function which throws an error, and handle the error in the calling function.

Hint/Explanation:

Errors can propagate up the call stack until caught in a try-catch block.

Solution:

function throwError() {

    throw new Error(“An error occurred”);

}

function catchError() {

    try {

        throwError();

    } catch (error) {

        console.error(“Caught error:”, error.message);

    }

}

catchError(); // Caught error: An error occurred

Exercise 5: Asynchronous Error Handling with Async/Await

Problem Statement:

Write an asynchronous function using async/await that catches and handles errors from a failed network request.

Hint/Explanation:

Async functions can use try-catch blocks to handle errors from asynchronous operations.

Solution:

async function fetchData(url) {

    try {

        const response = await fetch(url);

        const data = await response.json();

        console.log(data);

    } catch (error) {

        console.error(“Error fetching data:”, error.message);

    }

}

fetchData(‘https://invalidurl’); // Error fetching data: <error message>

Exercise 6: Throwing Errors

Problem Statement:

Write a function that checks if a user object is valid and throws an error if not, then catch and log this error when calling the function.

Hint/Explanation:

Use throw to raise custom errors and catch to handle them.

Solution:

function validateUser(user) {

    if (!user || !user.name) {

        throw new Error(“Invalid user object”);

    }

    console.log(“User is valid”);

}

try {

    validateUser(null);

} catch (error) {

    console.error(error.message); // Invalid user object

}

Exercise 7: Catching Multiple Errors

Problem Statement:

Create a function that can throw different types of errors based on input and use a single try-catch block to handle all these errors.

Hint/Explanation:

A single catch block can be used to handle different types of errors.

Solution:

function processInput(input) {

    if (typeof input !== ‘number’) {

        throw new TypeError(“Input must be a number”);

    } else if (input < 0) {

        throw new RangeError(“Input must be non-negative”);

    }

    return input * 2;

}

try {

    console.log(processInput(‘A’)); // TypeError: Input must be a number

    console.log(processInput(-1));  // RangeError: Input must be non-negative

} catch (error) {

    console.error(`${error.name}: ${error.message}`);

}

Exercise 8: Rethrowing Errors

Problem Statement:

Catch an error in a function, log it, and then rethrow it to be handled further up the call stack.

Hint/Explanation:

Rethrowing errors can be useful for both local handling and allowing higher-level handling.

Solution:

function mightThrow() {

    if (Math.random() > 0.5) {

        throw new Error(“Random error occurred”);

    }

    return “Success”;

}

function handleAndRethrow() {

    try {

        console.log(mightThrow());

    } catch (error) {

        console.error(“Handling error:”, error.message);

        throw error;

    }

}

try {

    handleAndRethrow();

} catch (error) {

    console.error(“Rethrown error:”, error.message);

}

Exercise 9: Finally in Async Functions

Problem Statement:

Implement a finally block in an asynchronous function to perform cleanup tasks, regardless of whether an error occurred.

Hint/Explanation:

The finally block in async functions is used for cleanup after try-catch blocks.

Solution:

async function performTask() {

    try {

        const result = await someAsyncOperation();

        console.log(result);

    } catch (error) {

        console.error(“Error occurred:”, error.message);

    } finally {

        console.log(“Cleanup actions”);

    }

}

performTask();

Exercise 10: Error Handling in Callbacks

Problem Statement:

Implement a function with a callback that follows the error-first callback pattern.

Hint/Explanation:

In the error-first callback pattern, the first argument of the callback is reserved for an error object, if any.

Solution:

function fetchData(callback) {

    // Simulate an API call

    setTimeout(() => {

        const error = Math.random() > 0.5 ? new Error(“Failed to fetch data”) : null;

        const data = error ? null : { id: 1, name: “John Doe” };

        callback(error, data);

    }, 1000);

}

fetchData((error, data) => {

    if (error) {

        return console.error(“Error:”, error.message);

    }

    console.log(“Data:”, data);

});

Delve into these exercises, test your skills, and share your insights. Let’s discuss how you handle errors in your JavaScript code! If you have any questions or additional tips, I’d love to hear them in the comments below. Let’s make our JavaScript code more robust together! 🚀🤝

#JavaScript #ErrorHandling #WebDevelopment #Programming #CodingExercises #JavaScriptLearning #SoftwareDevelopment #FrontEndDevelopment #BackEndDevelopment #FullStackDevelopment #TechCommunity #CodeNewbies #100DaysOfCode #Developers #LearnToCode #CodingIsFun #JavaScriptTips #TechEducation #CodingChallenges #SoftwareEngineering

These exercises cover a broad spectrum of error handling in JavaScript, from basic try-catch usage to handling errors in asynchronous code, providing valuable learning experiences in managing and responding to exceptions in various scenarios.