เราต้องปฏิบัติตามกฎบางอย่างเมื่อเราเอาชนะเมธอด ที่ส่งข้อยกเว้น
- เมื่อ วิธีคลาสหลัก ไม่มีข้อยกเว้น เมธอดคลาสลูก ไม่สามารถโยนข้อยกเว้นที่ตรวจสอบแล้ว แต่อาจมีข้อยกเว้นที่ไม่ได้ตรวจสอบ .
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 ที่มี ไม่ถูกเลือก ข้อยกเว้น เมธอดคลาสลูก สามารถโยนไม่มีหรือข้อยกเว้นที่ไม่ได้ตรวจสอบจำนวนเท่าใดก็ได้ แม้ว่าจะไม่ได้เกี่ยวข้องกัน
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