learn2kode.in

What Is try…catch in JavaScript?

The try…catch statement in JavaScript is used to handle runtime errors without stopping the execution of your program. It allows you to write safer code by catching errors and responding to them properly.

Why Use try…catch?

Without error handling, a single error can break the entire application. Using try…catch helps you:
Basic Syntax of try…catch
try {
  // Code that may cause an error
} catch (error) {
  // Code to handle the error
}
If an error occurs inside try, JavaScript immediately jumps to catch.
Simple try…catch Example
try {
  let result = JSON.parse('{name: "John"}');
} catch (error) {
  console.log("Invalid JSON format");
}
Accessing the Error Object
The catch block provides an error object containing useful information.
try {
  undefinedFunction();
} catch (error) {
  console.log(error.name);    // ReferenceError
  console.log(error.message); // undefinedFunction is not defined
}
Common Error Properties

Using try…catch with finally

The finally block runs always, whether an error occurs or not.
try {
  console.log("Trying...");
} catch (error) {
  console.log("Error occurred");
} finally {
  console.log("Execution completed");
}
Useful for:

try…catch with async / await

try…catch is commonly used with async JavaScript functions.
async function loadData() {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log("Failed to load data");
  }
}

When try…catch Does NOT Work

try {
  setTimeout(() => {
    undefinedFunction();
  }, 1000);
} catch (error) {
  console.log("This will NOT catch the error");
}

Best Practices for try…catch

Common Mistakes