Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript

Updated
•5 min read•View as Markdown
Error Handling in JavaScript
K
Always post blogs that is beginner friendly and try to explain complex topic in easy way into my blog.

let’s start with reality.

👉 errors avoid nahi hote 👉 errors handle kiye jaate hain


Sabse Pehle — Error Kya Hota Hai?

simple line:

👉 jab code expected tarike se run nahi karta → error


Ek Basic Example

console.log(name);

output:

ReferenceError: name is not defined

Types of Errors (Short Mein)

  • ReferenceError → variable exist nahi karta

  • TypeError → galat type pe kaam kar rahe ho

  • SyntaxError → code likhne mein mistake


Real Problem ⚠️

agar error aaya…

👉 pura program crash ho sakta hai 👉 baaki code run hi nahi karega


Example

console.log("Start");

console.log(name); // error

console.log("End");

output:

Start
(error)

👉 "End" kabhi run nahi hua


Yahan Entry Hoti Hai — try/catch 🚀


try aur catch — Basic Idea

👉 try = risky code likho 👉 catch = agar error aaye toh handle karo


Example

try {
  console.log(name);
} catch (error) {
  console.log("Error aa gaya bhai 😅");
}

Output

Error aa gaya bhai 😅

Important Point

👉 program crash nahi hua 👉 gracefully handle ho gaya


Real Life Example

socho tum ATM pe ho 💳

  • try → paise nikaalne ki koshish

  • catch → "insufficient balance" message

ATM blast nahi karta 😄 woh error handle karta hai.


try/catch Flow Samjho

try block run karo
↓
agar error aaya → catch run
↓
agar error nahi aaya → catch skip

finally Block — Hidden Hero ⭐

finally ka simple matlab:

👉 "yeh toh har condition mein chalega"


Example

try {
  console.log("Try chal raha hai");
} catch (err) {
  console.log("Error handle hua");
} finally {
  console.log("Finally hamesha chalega");
}

Output

Try chal raha hai
Finally hamesha chalega

Agar Error Aaye Toh?

try {
  console.log(name);
} catch (err) {
  console.log("Error handle hua");
} finally {
  console.log("Finally chalega");
}

Output

Error handle hua
Finally chalega

Use Case

👉 cleanup kaam 👉 closing resources 👉 logging


Throwing Custom Errors

kabhi kabhi tum khud error create karna chahte ho.


Example

const age = 15;

if (age < 18) {
  throw new Error("Not allowed 😡");
}

Result

👉 error manually throw hua


try/catch ke saath

try {
  const age = 15;

  if (age < 18) {
    throw new Error("Underage user");
  }

} catch (err) {
  console.log(err.message);
}

Output

Underage user

Real Life Example

login system 🔐

👉 password wrong → custom error 👉 email missing → custom error


Why Error Handling Matters

1. App crash se bachata hai

without handling:

👉 app band

with handling:

👉 app chalta rehta hai


2. Better User Experience

instead of:

❌ "Something went wrong"

you can show:

✅ "Server busy hai, thodi der baad try karo"


3. Debugging Easy

catch (err) {
  console.log(err);
}

👉 error trace milta hai


4. Production Ready Code

real apps mein:

👉 har API fail ho sakti hai 👉 network slow ho sakta hai


Async Error Handling ⚠️

important part.


Wrong Way ❌

try {
  fetch("https://api.com");
} catch (err) {
  console.log(err);
}

👉 yeh kaam nahi karega


Correct Way ✅

async function getData() {
  try {
    const res = await fetch("https://api.com");
    const data = await res.json();
    console.log(data);
  } catch (err) {
    console.log("Error:", err);
  }
}

Insight

👉 async code ke liye await + try/catch use karo


One Powerful Line

👉 errors avoid nahi hote — unhe handle karna padta hai


Flow of try and catch

        try
         ↓
   (error?)
    /     \
 yes       no
 ↓         ↓
catch     skip
   ↓
finally (always runs)

Real Example — API + Error Handling

async function loadUser() {
  try {
    console.log("Loading...");

    const res = await fetch("https://wrong-url.com");

    if (!res.ok) {
      throw new Error("API failed");
    }

    const data = await res.json();

    console.log(data);

  } catch (err) {
    console.log("Something went wrong:", err.message);
  } finally {
    console.log("Request finished");
  }
}

Output

Loading...
Error message
Request finished

Common Mistakes ❌

1. Empty catch

catch (err) {}

👉 debugging nightmare


2. Overusing try/catch

👉 har line pe mat lagao 👉 sirf risky code pe use karo


3. Ignoring error message

console.log("Error");

👉 useless


Best Practice

👉 meaningful messages 👉 logging 👉 user-friendly response


Assignment (Try Karo)

  1. ek error intentionally create karo

  2. try/catch se handle karo

  3. custom error throw karo

  4. async API call pe error handle karo


Final Thought

good developer woh nahi jo kabhi error nahi karta.

good developer woh hai jo:

👉 error ko control mein rakhta hai


One Line Summary

👉 try = risky code 👉 catch = error handle 👉 finally = always run


Connect with me here :

Twitter or X : https://x.com/Curious_Karann
LinkedIn : https://www.linkedin.com/in/karan-hingrajiya-82a78b2a4/

See you in the next blog !! until then keep growing and keep coding 🔥!!

More from this blog

Javascript : That most beginner's don't know

24 posts