Javascript

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.

Danilo Cavalcante

Working with web development since 2005, currently as a senior programmer analyst. Development, maintenance, and integration of systems in C#, ASP.Net, ASP.Net MVC, .Net Core, Web API, WebService, Integrations (SOAP and REST), Object-Oriented Programming, DDD, SQL, Git, and JavaScript

Recent Posts

Encapsulation and Abstraction in C#

Encapsulation and abstraction are two pillars of object-oriented programming (OOP) that play a vital role…

7 days ago

Polymorphism in C#: Object-Oriented Programming

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects to take on…

1 week ago

Understanding Inheritance in C#

Inheritance is a cornerstone of object-oriented programming (OOP) and one of its most powerful features.…

2 weeks ago

Classes and Objects in C#: Object-Oriented Programming

In the world of C# and object-oriented programming (OOP), classes and objects form the backbone…

2 weeks ago

Collections and LINQ Queries in C#

In modern C# programming, working with data collections is a common task. Understanding how to…

2 weeks ago

Exception Handling in C#: try-catch, finally, and Custom Exceptions

Exception handling is a critical part of writing robust and maintainable C# applications. It allows…

2 weeks ago