try...catch in JavaScript

🧠 What is try...catch?

The try...catch statement in JavaScript is used to handle errors gracefully during code execution. It allows you to run code that might throw an error and then catch that error without crashing the program. 🚧

🛠️ Syntax

Code Snippet

try {
  // Code that might throw an error
} catch (error) {
  // Code to handle the error
}

Note

🧪 Errors thrown in the try block are caught by the catch block.

✅ Basic Example

Code Snippet

try {
  const user = JSON.parse('{ name: "John" }'); // Invalid JSON
} catch (err) {
  console.log("Parsing error:", err.message);
}

In this example, malformed JSON will throw a SyntaxError, which is caught and logged.

📦 Real-World Example

Code Snippet

function getUserData(json) {
  try {
    const data = JSON.parse(json);
    console.log("User:", data.name);
  } catch (e) {
    console.error("Invalid JSON input:", e.message);
  }
}

getUserData('{"name": "Alice"}');     // ✅ Works
getUserData('invalid json');          // ❌ Caught by catch

🎯 Optional finally Block

The finally block runs no matter what — whether an error was thrown or not.

Code Snippet

try {
  // Code
} catch (err) {
  // Handle error
} finally {
  // Always runs
}

📍 Example with finally

Code Snippet

try {
  console.log("Trying...");
  throw new Error("Something failed");
} catch (e) {
  console.log("Caught error:", e.message);
} finally {
  console.log("Cleanup logic runs here");
}

Note

💡 finally is useful for cleanup tasks like closing a connection or hiding a loader.

🚫 What try...catch Can’t Do

  • Does not catch syntax errors during parsing time (before execution)
  • Does not catch errors thrown asynchronously (e.g., in setTimeout)

Code Snippet

try {
  setTimeout(() => {
    throw new Error("Async error");
  }, 1000);
} catch (e) {
  console.log("Won't catch this"); // ❌ Won't work
}

To catch asynchronous errors, you need to handle them within the async block:

Code Snippet

setTimeout(() => {
  try {
    throw new Error("Async error");
  } catch (e) {
    console.log("Caught async error:", e.message); // ✅
  }
}, 1000);

📌 Best Practices

  • 🎯 Only wrap code that may fail — don’t overuse try...catch
  • 🔍 Always log or handle errors meaningfully
  • 🧹 Use finally for cleanup logic (e.g., hide loading spinner)

📚 References

>>“Errors are part of life — handle them with grace and try...catch.”