Computer Screen

Error Handling in JavaScript: Try…Catch!

The try...catch statement allows you to handle exceptions (runtime errors) gracefully, preventing them from crashing your entire program. Here’s how it works:

Basic Syntax:

try {
  // Code that might throw an exception
  // ...
} catch (error) {
  // Code to handle the exception
  // ...
} finally {
  // Optional: Code that runs regardless of whether an exception occurred or not
  // ...
}

Example:

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

    return a / b;
  } catch (error) {
    console.error("Error:", error.message);
    // You can handle the error or rethrow it if needed
    // throw error;
  } finally {
    console.log("This code always runs, regardless of an exception");
  }
}

console.log(divide(10, 2)); // Output: 5
console.log(divide(10, 0)); // Output: Error: Cannot divide by zero
// Output: This code always runs, regardless of an exception

Common Use Cases:

Handling Expected Errors:

  • Use try...catch to handle errors that you anticipate might occur in your code.

Cleanup with Finally:

  • The finally block is optional but useful for cleanup tasks that need to run regardless of whether an exception occurred.

Rethrowing Exceptions:

  • You can rethrow an exception after handling it if you want to propagate it up the call stack.

Built-in Error Types:

JavaScript has several built-in error types, including Error, SyntaxError, ReferenceError, TypeError, etc.

try {
  // Code that might throw an exception
  throw new TypeError("This is a custom type error");
} catch (error) {
  console.error("Error:", error.message);
} finally {
  console.log("Cleanup code");
}

Async/Await:

try...catch is also used with asynchronous code when using async/await:

async function fetchData() {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Error fetching data:", error.message);
    throw error; // Rethrow if needed
  }
}

// Usage:
fetchData().then(data => console.log("Data:", data)).catch(err => console.error("Fetch error:", err));

Conclusion:

try...catch is a crucial tool for managing errors in JavaScript, allowing you to gracefully handle exceptions and ensure your program continues running smoothly. Use it to handle expected errors, clean up resources, and maintain a robust application.

Leave a Reply

Your email address will not be published. Required fields are marked *


Categories


Tag Cloud

.net algorithms angular api Array arrays async asynchronous basic-concepts big o blazor c# classes code components containers control-structures csharp data structures data types dictionaries docker dom dotnet framework functions git guide Inheritance javascript json leetcode linq lists loops methods MVC npm object oriented programming oop operators sorted try catch typescript web framework