try...catch...finally in JavaScript

🛠 What is try...catch...finally?

The try...catch...finally statement is a powerful control structure in JavaScript that helps you manage exceptions (errors) while ensuring certain code always runs.

try: Executes code that might throw an error ⚠️ catch: Executes if an error is thrown 🔁 finally: Always executes, regardless of error — often used for cleanup

🧪 Syntax

Code Snippet

try {
  // risky code
} catch (error) {
  // handle error
} finally {
  // always run this
}

📦 Example

Code Snippet

function divide(a, b) {
  try {
    console.log("Attempting division...");
    if (b === 0) throw new Error("Cannot divide by zero");
    console.log("Result:", a / b);
  } catch (err) {
    console.error("Error:", err.message);
  } finally {
    console.log("Division attempt finished.");
  }
}

divide(10, 2);  // ✅
divide(10, 0);  // ❌

🔍 Output

When b = 2:

Code Snippet

Attempting division...
Result: 5
Division attempt finished.

When b = 0:

Code Snippet

Attempting division...
Error: Cannot divide by zero
Division attempt finished.

📌 Use Cases for finally

  • 🧹 Clean up resources (close files, DB connections, etc.)
  • 🔁 Stop a loader or spinner after async operations
  • 📋 Log completion of operations regardless of success or failure

📍 finally Still Runs After return

Code Snippet

function testFinally() {
  try {
    return "Returning from try";
  } catch (e) {
    return "Returning from catch";
  } finally {
    console.log("This runs even after return!");
  }
}

console.log(testFinally());

Note

💡 Even if a return happens inside try or catch, the finally block still executes!

⛔ What finally Doesn't Do

  • 🚫 It cannot suppress an error — if not caught, it still bubbles up after finally runs
  • 🚫 It can't skip execution — it will always run unless the script is forcibly terminated

🔗 References

>>“Handle errors smartly, clean up always — that's the magic of try...catch...finally.”