DEV Community

Vamshi Krishna
Vamshi Krishna

Posted on

Understanding `try...catch` and `Promises` in JavaScript

try...catch

The try...catch block is used in JavaScript for handling errors or exceptions. It allows you to execute code that might throw an error and handle that error gracefully, instead of letting it crash the program.

Syntax:

try {
    // Code that might throw an error
    let result = riskyOperation();
    console.log(result);
} catch (error) {
    // Handle the error
    console.error("Something went wrong:", error);
}
Enter fullscreen mode Exit fullscreen mode

Example:

try {
    let num = JSON.parse("invalid JSON string");
    console.log(num);
} catch (error) {
    console.error("Error parsing JSON:", error.message); // Output: Error parsing JSON: Unexpected token i
}
Enter fullscreen mode Exit fullscreen mode

In this example, the invalid JSON throws an error, but the catch block catches it and logs a user-friendly message instead of breaking the application.

Promises

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. Promises allow us to write asynchronous code in a more manageable way without deeply nested callbacks (callback hell).

A promise can be in one of three states:

  • Pending: The initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Example:

const myPromise = new Promise((resolve, reject) => {
    let success = true; // Simulate success or failure

    setTimeout(() => {
        if (success) {
            resolve("Promise fulfilled!");
        } else {
            reject("Promise rejected!");
        }
    }, 1000);
});

myPromise
    .then((message) => {
        console.log(message); // Output: Promise fulfilled! (if success is true)
    })
    .catch((error) => {
        console.error(error); // Output: Promise rejected! (if success is false)
    });
Enter fullscreen mode Exit fullscreen mode

In this example, myPromise simulates an asynchronous operation that either resolves successfully or rejects with an error. The .then() method is used to handle the successful result, and .catch() is used for errors.

Combining try...catch with Promises (Async/Await)

When working with async/await in modern JavaScript, you can use try...catch for error handling with Promises.

Example:

async function fetchData() {
    try {
        let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("Fetch failed:", error);
    }
}

fetchData();
Enter fullscreen mode Exit fullscreen mode

In this example, the try...catch block catches any errors that occur during the asynchronous fetch operation.

Key Takeaways

  • try...catch: Handles synchronous and asynchronous errors, allowing you to manage exceptions and prevent crashes.
  • Promises: A way to handle asynchronous code, with .then() for success and .catch() for errors.
  • Async/Await + Try/Catch: Provides a cleaner way to write asynchronous code with promises while using try...catch for error handling.

Top comments (0)