मैं कोड पर ठोकर खाई कुछ इस तरह लग रही है:
void run() {
try {
doSomething();
} catch (Exception ex) {
System.out.println("Error: " + ex);
throw ex;
}
}
void doSomething() {
throw new RuntimeException();
}
यह कोड मुझे आश्चर्यचकित करता है क्योंकि ऐसा लगता है कि run()
-मैथोड एक को फेंकने में सक्षम है Exception
, क्योंकि यह पकड़ता है Exception
और फिर इसे हटा देता है, लेकिन विधि को फेंकने की घोषणा नहीं की जाती है Exception
और जाहिर तौर पर इसे करने की आवश्यकता नहीं है। यह कोड बस ठीक है (जावा 11 में कम से कम)।
मेरे उम्मीद होगी कि मैं घोषणा करने के लिए होता throws Exception
में run()
-method।
अतिरिक्त जानकारी
इसी तरह से, अगर doSomething
फेंकने की घोषणा की जाती है , IOException
तो केवल कोमथोड IOException
में घोषित करने की आवश्यकता run()
होती है, भले ही Exception
पकड़ा गया हो और फिर से फेंक दिया गया हो ।
void run() throws IOException {
try {
doSomething();
} catch (Exception ex) {
System.out.println("Error: " + ex);
throw ex;
}
}
void doSomething() throws IOException {
// ... whatever code you may want ...
}
सवाल
जावा आमतौर पर स्पष्टता पसंद करता है, इस व्यवहार के पीछे क्या कारण है? क्या यह हमेशा से ऐसा ही रहा है? जावा भाषा विशिष्टता में क्या है जो run()
विधि को throws Exception
ऊपर दिए गए कोड स्निपेट में घोषित करने की आवश्यकता नहीं है? (अगर मैं इसे जोड़ देता, तो IntelliJ मुझे चेतावनी देता है कि Exception
इसे कभी नहीं फेंका जाए)।
-source 1.6
ध्वज का संकलन उम्मीद के अनुरूप संकलन त्रुटि को जन्म देता है। स्रोत संगतता 7 के साथ संकलन संकलन त्रुटि को नहीं बढ़ाता
In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions : 1. 1. The try block is able to throw it. 2. There are no other preceding catch blocks that can handle it. 3. It is a subtype or supertype of one of the catch clause's exception parameters.
javac
- मैं उन मामलों में भाग रहा हूं जहां ग्रहण संकलक अधिक उदार था।