JavaScript में त्रुटि और अपवाद प्रबंधन try, catch, finally, और throw स्टेटमेंट्स का उपयोग करके किया जाता है। यह एप्लिकेशन को क्रैश होने से बचाता है और उपयोगकर्ता अनुभव को बेहतर बनाता है।
उदाहरण: विभाजन कैलकुलेटर
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.sample { font-size: 18px; font-weight: 500; }
input { padding: 8px; margin: 5px; border: 1px solid #ccc; border-radius: 4px; }
button { padding: 8px 16px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #0056b3; }
</style> </head> <body>
<h1>त्रुटि और अपवाद प्रबंधन उदाहरण</h1>
<div class="sample"></div>
<input class="inputNum" type="number" placeholder="पहली संख्या" />
<input class="inputNum" type="number" placeholder="दूसरी संख्या" />
<button class="Check">विभाजित करें</button>
<h3>ऊपर दिए गए बटन पर क्लिक करके विभाजन करें</h3>
<script>
let sampleEle = document.querySelector(".sample");
document.querySelector(".Check").addEventListener("click", () => {
const num = document.querySelectorAll(".inputNum")[0].value;
const num1 = document.querySelectorAll(".inputNum")[1].value;
try {
if (num === "" || num1 === "") throw "कृपया दोनों संख्याएं दर्ज करें";
if (num1 === "0") throw "शून्य से विभाजन संभव नहीं";
if (isNaN(num) || isNaN(num1)) throw "केवल संख्याएं दर्ज करें";
sampleEle.innerHTML = `${num} ÷ ${num1} = ${num / num1}`;
} catch (e) {
sampleEle.innerHTML = "त्रुटि: " + e;
sampleEle.style.color = "#d32f2f";
} finally {
console.log("गणना प्रयास पूरा हुआ");
}
});
</script> </body> </html>
आउटपुट
जब दूसरी संख्या 0 दर्ज करके "विभाजित करें" क्लिक किया जाता है, तो त्रुटि संदेश "त्रुटि: शून्य से विभाजन संभव नहीं" प्रदर्शित होता है।
त्रुटि प्रकार और उपयोग:
- ReferenceError: अघोषित वेरिएबल एक्सेस करने पर
- TypeError: गलत प्रकार पर ऑपरेशन करने पर
- RangeError: संख्या सीमा से बाहर होने पर
- SyntaxError: कोड सिंटैक्स गलत होने पर
- कस्टम त्रुटि:
throw "संदेश"याthrow new Error("संदेश")
finally ब्लॉक: हमेशा निष्पादित होता है, चाहे त्रुटि हो या न हो - संसाधन सफाई के लिए उपयोगी।