← Back to JavaScript Course | Chapter 8: Error Handling | Lesson 1 of 6

JS एरर हैंडलिंग

Error handling यह plan करना है कि कुछ गलत होने पर आपका program क्या करता है, जैसे car में spare tire रखना। यह एक समस्या को सब कुछ बर्बाद करने से रोकता है।
Syntax
javascript
try {
  // code that may throw
} catch (error) {
  // handle error
}

Error Handling क्या है

Error handling का मतलब है यह अंदाज़ा लगाना कि कुछ operations fail हो सकते हैं और ऐसा code लिखना जो पूरे program को एक uncaught exception से crash होने देने के बजाय अच्छे से respond करे।

एक try/catch block इसके लिए मुख्य tool है, जो risky code को चलने देता है जबकि उसके fail होने पर एक तय fallback path भी रखता है।

उदाहरण: What Is Error Handling

javascript
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
  // Call `JSON.parse("not valid json")`
  // Call `JSON.parse("not valid json")`
  JSON.parse("not valid json");
// Catch any error, bound to `error`
// Catch any error, bound to `error`
} catch (error) {
  // Print `"Handled gracefully:", error.message` to the console
  // Print `"Handled gracefully:", error.message` to the console
  console.log("Handled gracefully:", error.message);
}

Errors Throw करना

आप throw से एक समस्या उठाते हैं, जो तुरंत normal execution को रोक देता है और इसे संभालने में सक्षम सबसे पास के catch block को ढूंढता है, ज़रूरत पड़ने पर call stack को unwind करते हुए।

आप JavaScript में कोई भी value throw कर सकते हैं, पर एक Error object (या उसका कोई subclass) throw करना standard practice है क्योंकि यह एक उपयोगी stack trace capture करता है।

उदाहरण: Throwing Errors

javascript
// Define the function `withdraw` taking `balance`, `amount`
// Define the function `withdraw` taking `balance`, `amount`
function withdraw(balance, amount) {
  // Check whether `amount > balance`
  // Check whether `amount > balance`
  if (amount > balance) {
    // Throw a new `Error` with message "Insufficient funds"
    // Throw a new `Error` with message "Insufficient funds"
    throw new Error("Insufficient funds");
  }
  // Return `balance - amount` from this function
  // Return `balance - amount` from this function
  return balance - amount;
}
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
  // Call `withdraw(100, 200)`
  // Call `withdraw(100, 200)`
  withdraw(100, 200);
// Catch any error, bound to `e`
// Catch any error, bound to `e`
} catch (e) {
  // Print `e.message` to the console
  // Print `e.message` to the console
  console.log(e.message);
}

अलग-अलग स्थितियाँ संभालना

अलग-अलग failures को अलग-अलग responses चाहिए होते हैं — एक गायब network connection के लिए retry सही हो सकता है, जबकि invalid user input को चुपचाप fail होने के बजाय एक message दिखाना चाहिए।

हर error को एक जैसा ही treat करना, एक generic catch-all message के साथ, अक्सर उस उपयोगी जानकारी को छुपा देता है जो user या developer की मदद कर सकती थी।

उदाहरण: Handling Different Situations

javascript
// Define the function `processInput` taking `value`
// Define the function `processInput` taking `value`
function processInput(value) {
  // Check whether `typeof value !== "number"`
  // Check whether `typeof value !== "number"`
  if (typeof value !== "number") {
    // Print "Invalid input, please enter a number" to the console
    // Print "Invalid input, please enter a number" to the console
    console.log("Invalid input, please enter a number");
  // Otherwise, run this branch
  // Otherwise, run this branch
  } else {
    // Print `"Processing:", value` to the console
    // Print `"Processing:", value` to the console
    console.log("Processing:", value);
  }
}
// Call `processInput("abc")`
// Call `processInput("abc")`
processInput("abc");

अच्छी Error Handling

अच्छी error handling समस्या को diagnose करने के लिए error.message या किसी custom error type के ज़रिए काफी detail देती है, बिना end user को stack traces या database details जैसी sensitive internal चीज़ें दिखाए।

उदाहरण: Good Error Handling

javascript
try {
  throw new Error("Database connection failed");
} catch (error) {
  console.log("Error occurred:", error.message); // useful detail, no internals leaked
}

Error Handling Best Practices

एक सामान्य नियम के तौर पर, errors को वहाँ पास catch करें जहाँ आप असल में उनके बारे में कुछ उपयोगी कर सकते हैं, और जिन errors को आप संभाल नहीं सकते उन्हें किसी ऐसी boundary तक propagate होने दें जो संभाल सके।

काफी context के साथ errors को log करना (कौन सा operation fail हुआ, किस input के साथ) बाद में production issues को debug करना कहीं आसान बना देता है।

उदाहरण: Error Handling Best Practices

javascript
// Define the function `riskyOperation` with no parameters
// Define the function `riskyOperation` with no parameters
function riskyOperation() {
  // Throw a new `Error` with message "Something failed"
  // Throw a new `Error` with message "Something failed"
  throw new Error("Something failed");
}
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
  // Call `riskyOperation()`
  // Call `riskyOperation()`
  riskyOperation();
// Catch any error, bound to `e`
// Catch any error, bound to `e`
} catch (e) {
  // Print `"Handled where we can act:", e.message` to the console
  // Print `"Handled where we can act:", e.message` to the console
  console.log("Handled where we can act:", e.message);
}
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी error को catch करना और catch block में कुछ न करना, जो problem को छुपा देता है।
  2. plain strings throw करना, जैसे throw "oops", जो कोई stack trace नहीं देता; throw new Error("oops") करें।
  3. एक बड़े try में हर error handle करने की कोशिश करना, इसलिए असली कारण साफ नहीं रहता।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.