"मैं आपको इस बारे में थोड़ा बताना चाहता हूं कि अपवाद कैसे काम करते हैं। नीचे दिए गए उदाहरण से आपको अंदाजा लगना चाहिए कि क्या होता है:"
class ExceptionExampleOriginal
{
public static void main(String[] args)
{
System.out.println("main begin");
try
{
System.out.println("main before call");
method1();
System.out.println("main after call");
}
catch (RuntimeException e)
{
String s = e.getMessage();
System.out.println(s);
}
System.out.println("main end");
}
public static void method1()
{
System.out.println("method1 begin");
method2();
System.out.println("method1 end");
}
public static void method2()
{
System.out.println("method2");
String s = "Message: Unknown Exception";
throw new RuntimeException(s);
}
}
public class ExceptionExample
{
private static Exception exception = null;
public static void main(String[] args)
{
System.out.println("main begin");
System.out.println("main before call");
method1();
if (exception == null)
{
System.out.println("main after call");
}
else if (exception instanceof RuntimeException)
{
RuntimeException e = (RuntimeException) exception;
exception = null;
String s = e.getMessage();
System.out.println(s);
}
System.out.println("main end");
}
public static void method1()
{
System.out.println("method1 begin");
method2();
if (exception != null) return;
System.out.println("method1 end");
}
public static void method2()
{
System.out.println("method2");
String s = "Message: Unknown Exception";
exception = new RuntimeException(s);
return;
}
}
"मैं पूरी तरह से खो गया हूँ।"
"ठीक है। मुझे समझाने दो कि क्या हो रहा है।"
"बाईं ओर के उदाहरण में, हम उत्तराधिकार में कुछ विधियों को कॉल करते हैं। में method2
, हम जानबूझकर एक अपवाद बनाते हैं और फेंकते हैं (हम एक त्रुटि बनाते हैं)।"
"दाईं ओर का उदाहरण दिखाता है कि क्या हो रहा है।"
"देखें method2
। एक अपवाद बनाने के बजाय, हम एक RuntimeException
वस्तु बनाते हैं, इसे स्थैतिक चर में सहेजते हैं exception
, और फिर तुरंत एक return
बयान का उपयोग करके विधि से बाहर निकल जाते हैं।"
"में method1
, कॉल करने के बाद method2
, हम जाँचते हैं कि क्या कोई अपवाद है। यदि कोई अपवाद है, तो method1
एक बार में समाप्त हो जाता है। जावा में प्रत्येक (!) विधि कॉल के बाद इस तरह की जाँच अप्रत्यक्ष रूप से की जाती है।"
"बहुत खूब!"
"वाह सही है।"
"दाएं कॉलम में, मैंने मुख्य विधि का उपयोग यह दिखाने के लिए किया है कि लगभग क्या होता है जब एक ट्राइ-कैच निर्माण का उपयोग करके एक अपवाद पकड़ा जाता है। यदि कोई अपवाद नहीं है, तो सब कुछ अपेक्षित रूप से चलता रहता है। यदि कोई अपवाद है और यह कैच स्टेटमेंट में निर्दिष्ट एक ही प्रकार है, फिर हम इसे हैंडल करते हैं।"
"क्या करें throw
और क्या instanceof
मतलब है? "
"अंतिम पंक्ति को देखें: throw new RuntimeException(s);
. इस तरह आप एक अपवाद बनाते और फेंकते हैं। हम उस पर अभी काम नहीं करेंगे। यह सिर्फ एक उदाहरण था।"
"हम a instanceof B
यह जांचने के लिए उपयोग करते हैं कि क्या वस्तु a
प्रकार की है B
, अर्थात क्या चर अपवाद द्वारा संदर्भित वस्तु एक रनटाइम अपवाद है। यह एक बूलियन अभिव्यक्ति है।"
"मुझे लगता है कि मुझे मिल गया। लगभग।"
GO TO FULL VERSION