try... catch (प्रयास ... क्याच)
In programming errors happen for various reasons, some happen from code errors, some due to wrong input, and other unforeseeable things. When an error happens, the code stops and generates an error message usually seen in the console.
प्रोग्रामिंग त्रुटिहरूमा विभिन्न कारणहरूको लागि हुन्छ, केहि कोड त्रुटिहरूबाट हुन्छन्, केहि गलत इनपुटको कारण, र अन्य अप्रत्याशित चीजहरूको कारण। जब एउटा त्रुटि हुन्छ, कोड रोकिन्छ र सामान्यतया कन्सोलमा देखिने त्रुटि सन्देश उत्पन्न गर्दछ ।
Instead of halting the code execution, we can use the try...catch construct that allows catching errors without dying the script. The try...catch construct has two main blocks; try and then catch.
कोड कार्यान्वयन रोक्नुको सट्टा, हामी प्रयास गर्नुहोस् ... क्याच निर्माण जसले स्क्रिप्टको मृत्यु बिना त्रुटिहरू समात्न अनुमति दिन्छ। 'कोशिश... क्याच 'कन्स्ट्रक्टमा दुई मुख्य ब्लकहरू छन्; 'कोशिश' और फिर 'कैच'।
try {
// code...
} catch (err) {
// error handling
}
At first, the code in the try block is executed. If no errors are encountered then it skips the catch block. If an error occurs then the try execution is stopped, moving the control sequence to the catch block. The cause of the error is captured in err variable.
सुरुमा, प्रयास ब्लकमा कोड कार्यान्वयन गरिन्छ। यदि कुनै त्रुटिहरू देखा परेनन् भने यसले क्याच ब्लक छोड्छ। यदि कुनै त्रुटि उत्पन्न हुन्छ भने प्रयास कार्यान्वयन रोकिन्छ, नियन्त्रण अनुक्रमलाई क्याच ब्लकमा सार्दछ। त्रुटिको कारण त्रुटि चरमा कब्जा गरिएको छ।
try {
// code...
alert('Welcome to Learn JavaScript');
asdk; // error asdk variable is not defined
} catch (err) {
console.log("Error has occurred");
}
try...catch works for runtime errors meaning that the code must be runnable and synchronous.
प्रयास ... क्याच रनटाइम त्रुटिहरूको लागि काम गर्दछ जसको अर्थ कोड रनेबल र सिंक्रोनस हुनुपर्दछ।
To throw a custom error, a throw statement can be used. The error object, that gets generated by errors has two main properties.
अनुकूल त्रुटि फ्याँक्न, 'थ्रो' कथन प्रयोग गर्न सकिन्छ। त्रुटि वस्तु, जुन त्रुटिहरू द्वारा उत्पन्न हुन्छ, दुई मुख्य गुणहरू छन्।
- name: error name
message: details about the error
नाम: त्रुटि नाम
- सन्देश: त्रुटिको बारेमा विवरण
If we don't need an error message catch can omit it.
यदि हामीलाई 'त्रुटि' सन्देश आवश्यक छैन भने क्याचले यसलाई छोड्न सक्छ।