2013-10-16 12 views
8

मुझे Exception with Inheritance में कोई संदेह है।क्यों जावा ArrayIndexOutOfBound अपवाद इंडेक्सऑफॉफउंड अपवाद फेंकने योग्य नहीं है?

क्यों

public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException

और फिर

public class IndexOutOfBoundsException extends RuntimeException

और फिर

public class RuntimeException extends Exception

क्यों नहीं

public class ArrayIndexOutOfBoundsException extends Exception

क्यों इस पदानुक्रम बनाए रखा है .. किसी भी मार्गदर्शन उपयोगी होगा?

उत्तर

7

इसका उद्देश्य पदानुक्रम रखने का इरादा है जो समझ में आता है, और समूह से संबंधित अपवादों में भी कार्य करता है।

इसके अलावा, अगर आपको पता है कि IndexOutOfBoundsException क्या है, और कोई आपको एक और अपवाद देता है जो इसे विस्तारित करता है, तो आप तुरंत इस तथ्य से जानकारी एकत्र कर सकते हैं। इस मामले में, कुछ शामिल वस्तुओं में एक निश्चित सीमा के भीतर इंडेक्स रहते हैं।

यदि प्रत्येक अपवाद Exception या RuntimeException (चाहे उसकी घटना की जांच की जानी चाहिए या गैर-जांच की गई हो), और इसका नाम कुछ अस्पष्ट था, तो आपको इसका कोई संकेत नहीं होगा कि यह क्या प्रतिनिधित्व कर सकता है।

निम्नलिखित कोड पर विचार करें।

try { 
    for (int i = 0; i < limit; ++i) { 
     myCharArray[i] = myString.charAt(i); 
    } 
} 
catch (StringIndexOutOfBoundsException ex) { 
    // Do you need to treat string indexes differently? 
} 
catch (ArrayIndexOutOfBoundsException ex) { 
    // Perhaps you need to do something else when the problem is the array. 
} 
catch (IndexOutOfBoundsException ex) { 
    // Or maybe they can both be treated equally. 
    // Note: you'd have to remove the previous two `catch`. 
} 
1

क्योंकि ArrayIndexOutOfBoundsExceptionIndexOutOfBoundsException है।

9

ऐसा इसलिए है क्योंकि ArrayIndexOutOfBoundsException भी IndexOutOfBoundsException और RuntimeException है।

आपके सुझाव में, ArrayIndexOutOfBoundsException केवल Exception होगा।

तो यदि आप केवल RuntimeException को पकड़ना चाहते हैं उदाहरण के लिए, ArrayIndexOutOfBoundsException पकड़ा नहीं जाएगा।

1

वह जगह है जहां विरासत तस्वीर में आती है, और विस्तारशीलता के मुख्य लक्ष्य के साथ विरासत के स्तर को स्वच्छ और केंद्रित रखने में मदद करता है। वहां ग्रेन में न केवल गलत हो सकता है बल्कि स्ट्रिंग आदि में भी इंडेक्स हो सकता है। एचटीएच

संबंधित मुद्दे