Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript: Try, Catch, Finally

Updated
β€’3 min readβ€’View as Markdown
Error Handling in JavaScript: Try, Catch, Finally
A
Web Developer

⚠️ What Are Errors in JavaScript?

Errors are problems that occur during code execution and stop your program from running correctly.

πŸ”Ή Common Types of Errors

  1. Syntax Error
    Mistake in code structure

    console.log("Hello" // missing )
    
  2. Reference Error

    Using a variable that is not defined

    console.log(name); // name is not defined
    
  3. Type Error

    Wrong operation on a data type

    let num = 10;
    num.toUpperCase(); // number has no toUpperCase()
    
  4. Range Error

    Value out of allowed range

    let arr = new Array(-1);
    

🚨 Real Runtime Error Example

let user = null;
console.log(user.name); // ❌ TypeError

πŸ‘‰ This crashes your app if not handled.


πŸ› οΈ Using try...catch

try...catch helps handle errors gracefully instead of crashing.

try {
  let user = null;
  console.log(user.name);
} catch (error) {
  console.log("Something went wrong:", error.message);
}

βœ… Output:

Something went wrong: Cannot read properties of null

πŸ”„ Execution Flow (Try β†’ Catch β†’ Finally)

Start
  ↓
Try Block
  ↓
Error?
 /   \
Yes   No
 ↓     ↓
Catch  Skip Catch
  ↓
Finally (always runs)
  ↓
End

🧩 The finally Block

finally always runs β€” whether an error occurs or not.

try {
  console.log("Try block running");
} catch (err) {
  console.log("Error caught");
} finally {
  console.log("Always runs");
}

🎯 Throwing Custom Errors

You can create your own errors using throw.

function withdraw(amount) {
  if (amount > 1000) {
    throw new Error("Limit exceeded");
  }
  return "Withdrawal successful";
}

try {
  withdraw(2000);
} catch (err) {
  console.log(err.message);
}

🌍 Real-World Example (Bank System)

function transfer(balance, amount) {
  try {
    if (amount > balance) {
      throw new Error("Insufficient balance");
    }
    console.log("Transfer successful");
  } catch (err) {
    console.log("Transaction failed:", err.message);
  } finally {
    console.log("Transaction attempt completed");
  }
}

transfer(500, 700);

πŸ’‘ Why Error Handling Matters

βœ… Prevents App Crash

Without handling β†’ app stops ❌

With handling β†’ app continues βœ…

βœ… Graceful Failure

Instead of breaking:

"Error occurred"

You show:

"Something went wrong, please try again"

βœ… Better Debugging

  • Error messages help identify bugs faster

  • Stack traces show where the issue occurred

βœ… Improves User Experience

Users don’t see broken screens πŸ‘


🧭 Graceful Failure Example

❌ Bad:

console.log(user.name);

βœ… Good:

if (user) {
  console.log(user.name);
} else {
  console.log("User not available");
}

πŸ” Debugging Benefits

  • Helps locate exact issue

  • Saves development time

  • Makes code maintainable

  • Easier testing & logging


🎯 Quick Summary

  • Errors are unavoidable β€” handling them is essential

  • Use try...catch to prevent crashes

  • Use finally for cleanup tasks

  • Use throw to create custom errors

  • Always aim for graceful failure