हमें एक्सेप्शन थ्रो करने वाले मेथड को ओवरराइड करते समय कुछ नियमों का पालन करना आवश्यक है।
- जब पैरेंट क्लास मेथड कोई एक्सेप्शन नहीं थ्रो करता, तो चाइल्ड क्लास मेथड कोई चेक्ड एक्सेप्शन नहीं थ्रो कर सकता, लेकिन यह कोई भी अनचेक्ड एक्सेप्शन थ्रो कर सकता है।
class Parent {
void doSomething() {
// ...
}
}
class Child extends Parent {
void doSomething() throws IllegalArgumentException {
// ...
}
}
- जब पैरेंट क्लास मेथड एक या अधिक चेक्ड एक्सेप्शन थ्रो करता है, तो चाइल्ड क्लास मेथड वही एक्सेप्शन या उसके सबक्लास थ्रो कर सकता है, या कोई एक्सेप्शन नहीं थ्रो कर सकता, लेकिन नए/व्यापक चेक्ड एक्सेप्शन नहीं थ्रो कर सकता।
class Parent {
void doSomething() throws IOException, ParseException {
// ...
}
void doSomethingElse() throws IOException {
// ...
}
}
class Child extends Parent {
void doSomething() throws IOException {
// ...
}
void doSomethingElse() throws FileNotFoundException, EOFException {
// ... (FileNotFoundException, EOFException, IOException के सबक्लास हैं)
}
}
- जब पैरेंट क्लास मेथड के थ्रो क्लॉज में अनचेक्ड एक्सेप्शन होता है, तो चाइल्ड क्लास मेथड कोई भी या किसी भी संख्या में अनचेक्ड एक्सेप्शन थ्रो कर सकता है, भले ही वे संबंधित न हों।
class Parent {
void doSomething() throws IllegalArgumentException {
// ...
}
}
class Child extends Parent {
void doSomething() throws ArithmeticException, BufferOverflowException {
// ...
}
}
उदाहरण
import java.io.*;
class SuperClassTest{
public void test() throws IOException {
System.out.println("SuperClassTest.test() method");
}
}
class SubClassTest extends SuperClassTest {
public void test() {
System.out.println("SubClassTest.test() method");
}
}
public class OverridingExceptionTest {
public static void main(String[] args) {
SuperClassTest sct = new SubClassTest();
try {
sct.test();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
आउटपुट
SubClassTest.test() method
सबक्लास मेथड पैरेंट के चेक्ड एक्सेप्शन (IOException) को थ्रो नहीं करता, जो अनुमत है। पैरेंट रेफरेंस से कॉल करने पर भी कोई एक्सेप्शन नहीं थ्रो होता।