এক্সেপশন থ্রো করার মেথড ওভাররাইড করার সময় আমাদের কিছু নियमাবলী মেনে চলতে হয়।
- যখন প্যারেন্ট ক্লাস মেথড কোনো এক্সেপশন থ্রো করে না, তখন চাইল্ড ক্লাস মেথড কোনো চেকড এক্সেপশন থ্রো করতে পারে না, কিন্তু এটি যেকোনো অনচেকড এক্সেপশন থ্রো করতে পারে।
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 {
// ...
}
}
- যখন প্যারেন্ট ক্লাস মেথড-এ throws clause-এ একটি অনচেকড এক্সেপশন থাকে, তখন চাইল্ড ক্লাস মেথড কোনো বা যেকোনো সংখ্যক অনচেকড এক্সেপশন থ্রো করতে পারে, সেগুলো আপসে রিলেটেড নাও হলে চলে।
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