📘 Lesson · Lesson 45
Error Handling: try...catch
Error Handling: try...catch
Why Handle Errors
let data = JSON.parse("not valid json"); // ✗ throws an error
console.log("This line NEVER runs"); // the script has crashed
When JavaScript hits an error it cannot recover from, it stops executing the rest of your script. One bad line — a failed network request, malformed JSON, a missing element — and everything after it silently dies. Error handling lets you CATCH that failure, deal with it gracefully (show a friendly message, retry, use a fallback), and keep the page working. Professional code anticipates that things will go wrong, because they always do.
try...catch — the basic structure
try {
// Code that MIGHT fail
let data = JSON.parse(userInput);
console.log(data.name);
} catch (error) {
// Runs ONLY if something in try{} threw an error
console.log("Could not parse:", error.message);
}
console.log("The script continues normally"); // ✓ this still runs
Put risky code inside
try { }. If any line in there throws, JavaScript immediately jumps to catch (error) { }, skipping the rest of the try block. The error parameter holds an object describing what went wrong. Crucially, the script does NOT crash — execution continues after the catch. Only wrap code that might realistically fail; wrapping everything in try/catch hides bugs you'd rather see. Typical candidates: JSON.parse, network requests, and anything touching external data.The Error Object
try {
undefinedFunction();
} catch (error) {
console.log(error.name); // "ReferenceError"
console.log(error.message); // "undefinedFunction is not defined"
console.log(error.stack); // where it happened (for debugging)
}
The object handed to
catch has three useful properties. error.name is the error's TYPE (like TypeError), error.message is the human-readable description — this is what you usually show or log — and error.stack shows the call trail leading to the failure, invaluable when debugging. Show error.message to users if it's helpful, but never show the raw stack: it can leak details about your code.throw and finally
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero"); // create your OWN error
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (e) {
console.log(e.message); // "Cannot divide by zero"
} finally {
console.log("Always runs — success or failure");
}
throw new Error("message") lets you raise your own error when something is wrong — a validation failure, an impossible state, a bad argument. It stops the function instantly and jumps to the nearest catch. This is how you signal "this cannot proceed" clearly, rather than silently returning undefined. finally runs no matter what — after success, after an error, even after a return. Use it for cleanup: hiding a loading spinner, closing a connection, re-enabling a button.Common Error Types
| Error | Cause |
|---|---|
| ReferenceError | Using a variable that doesn't exist (or is in the TDZ) |
| TypeError | Using a value the wrong way — e.g. null.name, calling a non-function |
| SyntaxError | Invalid code — a typo, a missing bracket, bad JSON |
| RangeError | A number outside its allowed range |
Learning to read error names saves hours. ReferenceError usually means a typo in a variable name, or using
let/const before their declaration line (the temporal dead zone). TypeError — the most common in DOM work — almost always means something is null or undefined: querySelector found nothing, or you forgot the parentheses on a function call. SyntaxError means the code couldn't even be read; check brackets and quotes. Read the message, note the line number, then look there first.Exam Corner
Q: What happens to a script when an uncaught error occurs? It stops executing — the rest of the code never runs.
Q: What does the catch block receive? An Error object with name, message, and stack properties.
Q: When does the finally block run? Always — whether the try succeeded or an error was caught.
Q: How do you raise your own error?
Q: What usually causes a TypeError in DOM code? Using a null element — querySelector found nothing.
Q: What does the catch block receive? An Error object with name, message, and stack properties.
Q: When does the finally block run? Always — whether the try succeeded or an error was caught.
Q: How do you raise your own error?
throw new Error("message")Q: What usually causes a TypeError in DOM code? Using a null element — querySelector found nothing.
Errors क्यों संभालें
let data = JSON.parse("not valid json"); // ✗ error phenkta hai
console.log("Yeh line KABHI nahi chalti"); // script crash ho gayi
जब JavaScript ऐसे error से टकराता है जिससे उबर नहीं सकता, यह आपकी बाकी script चलाना बंद कर देता है. एक बुरी line — असफल network request, बिगड़ा JSON, गायब element — और उसके बाद सब कुछ चुपचाप मर जाता है. Error handling आपको उस विफलता को PAKADNE, शालीनता से निपटने (दोस्ताना message दिखाना, फिर कोशिश, fallback use करना), और page चालू रखने देता है. Professional code मानकर चलता है कि चीज़ें गलत होंगी, क्योंकि वे हमेशा होती हैं.
try...catch — बुनियादी ढांचा
try {
// Code jo fail HO SAKTA hai
let data = JSON.parse(userInput);
console.log(data.name);
} catch (error) {
// SIRF tab chalta jab try{} me kuch error phenke
console.log("Parse nahi kar paye:", error.message);
}
console.log("Script normal jaari rehti hai"); // ✓ yeh phir bhi chalta
जोखिम भरा code
try { } के अंदर रखिए. अगर वहां कोई line error फेंके, JavaScript तुरंत catch (error) { } पर कूदता है, try block का बाकी छोड़ते. error parameter वह object रखता है जो बताता है क्या गलत हुआ. अहम बात, script crash NAHI होती; catch के बाद execution जारी रहता है. सिर्फ वह code लपेटिए जो वास्तव में fail हो सकता है; हर चीज़ को try/catch में लपेटना उन bugs को छुपाता है जिन्हें आप देखना चाहेंगे. सामान्य उम्मीदवार: JSON.parse, network requests, और बाहरी data छूने वाला कुछ भी.Error Object
try {
undefinedFunction();
} catch (error) {
console.log(error.name); // "ReferenceError"
console.log(error.message); // "undefinedFunction is not defined"
console.log(error.stack); // kahan hua (debugging ke liye)
}
catch को सौंपे object की तीन उपयोगी properties हैं. error.name error का TYPE है (जैसे TypeError), error.message इंसान के पढ़ने योग्य विवरण है — यही आप आमतौर पर दिखाते या log करते हैं — और error.stack विफलता तक ले जाने वाला call trail दिखाता है, debugging में अमूल्य. उपयोगी हो तो users को error.message दिखाइए, पर कच्चा stack कभी नहीं: यह आपके code के विवरण leak कर सकता है.throw और finally
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero"); // APNA error banao
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (e) {
console.log(e.message); // "Cannot divide by zero"
} finally {
console.log("Hamesha chalta — safalta ho ya vifalta");
}
throw new Error("message") आपको कुछ गलत होने पर अपना error उठाने देता है — validation विफलता, असंभव स्थिति, बुरा argument. यह function तुरंत रोककर निकटतम catch पर कूदता है. ऐसे ही आप साफ संकेत देते हैं "यह आगे नहीं बढ़ सकता," चुपचाप undefined लौटाने के बजाय. finally चाहे कुछ भी हो चलता है — सफलता के बाद, error के बाद, return के बाद भी. इसे cleanup के लिए use कीजिए: loading spinner छुपाना, connection बंद करना, button फिर से चालू करना.आम Error Types
| Error | कारण |
|---|---|
| ReferenceError | न मौजूद variable use करना (या TDZ में हो) |
| TypeError | Value का गलत इस्तेमाल — जैसे null.name, non-function call करना |
| SyntaxError | अमान्य code — typo, गायब bracket, बुरा JSON |
| RangeError | अनुमत सीमा से बाहर number |
Error नाम पढ़ना सीखना घंटों बचाता है. ReferenceError आमतौर पर variable नाम में typo, या
let/const को उनकी declaration line से पहले use करना (temporal dead zone) है. TypeError — DOM काम में सबसे common — लगभग हमेशा मतलब कुछ null या undefined है: querySelector को कुछ नहीं मिला, या आप function call के parentheses भूल गए. SyntaxError मतलब code पढ़ा ही नहीं जा सका; brackets और quotes जांचिए. Message पढ़िए, line number नोट कीजिए, फिर पहले वहीं देखिए.Exam Corner
Q: Uncaught error होने पर script का क्या होता है? यह चलना बंद कर देती है — बाकी code कभी नहीं चलता.
Q: catch block को क्या मिलता है? name, message, और stack properties वाला Error object.
Q: finally block कब चलता है? हमेशा — चाहे try सफल हो या error पकड़ा गया.
Q: अपना error कैसे उठाते हैं?
Q: DOM code में TypeError आमतौर पर किससे होता है? null element use करने से — querySelector को कुछ नहीं मिला.
Q: catch block को क्या मिलता है? name, message, और stack properties वाला Error object.
Q: finally block कब चलता है? हमेशा — चाहे try सफल हो या error पकड़ा गया.
Q: अपना error कैसे उठाते हैं?
throw new Error("message")Q: DOM code में TypeError आमतौर पर किससे होता है? null element use करने से — querySelector को कुछ नहीं मिला.
💻 Live Code Editor
इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का
console.log देखने के लिए F12 दबाइए.