เมื่อคุณพยายามที่จะจัดการกับข้อยกเว้น (ตรวจสอบ) ที่เกิดจากวิธีการเฉพาะ คุณต้องจับมันโดยใช้ ข้อยกเว้น class หรือ super class ของ Exception เกิดขึ้น
ในทำนองเดียวกันในขณะที่เอาชนะเมธอดของ super class หากมีข้อยกเว้น -
-
เมธอดในคลาสย่อยควรมีข้อยกเว้นหรือประเภทย่อยเหมือนกัน
-
เมธอดในคลาสย่อยไม่ควรโยน super type
-
คุณสามารถแทนที่ได้โดยไม่มีข้อยกเว้น
เมื่อคุณมีสามคลาสชื่อ Demo, SuperTest และ Super in (ลำดับชั้น) การสืบทอด หาก Demo และ SuperTest มีเมธอดชื่อ sample() .
ตัวอย่าง
class Demo {
public void sample() throws ArrayIndexOutOfBoundsException {
System.out.println("sample() method of the Demo class");
}
}
class SuperTest extends Demo {
public void sample() throws IndexOutOfBoundsException {
System.out.println("sample() method of the SuperTest class");
}
}
public class Test extends SuperTest {
public static void main(String args[]) {
Demo obj = new SuperTest();
try {
obj.sample();
}catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Exception");
}
}
} ผลลัพธ์
sample() method of the SuperTest class
หากคลาสที่คุณตรวจพบข้อยกเว้นไม่เหมือนกัน หรือ ข้อยกเว้น หรือ ซูเปอร์คลาสของข้อยกเว้นที่ยกขึ้น คุณจะได้รับข้อผิดพลาดเวลาคอมไพล์
ในทำนองเดียวกัน ในขณะที่แทนที่เมธอด ข้อยกเว้นที่ส่งออกมาควรเหมือนกัน หรือ ซูเปอร์คลาสของข้อยกเว้นที่ส่งโดยเมธอดที่ถูกแทนที่ มิฉะนั้นจะเกิดข้อผิดพลาดเวลาคอมไพล์
ตัวอย่าง
import java.io.IOException;
import java.io.EOFException;
class Demo {
public void sample() throws IOException {
System.out.println("sample() method of the Demo class");
}
}
class SuperTest extends Demo {
public void sample() throws EOFException {
System.out.println("sample() method of the SuperTest class");
}
}
public class Test extends SuperTest {
public static void main(String args[]) {
Demo obj = new SuperTest();
try {
obj.sample();
}catch (EOFException ex){
System.out.println("Exception");
}
}
} ผลลัพธ์
Test.java:12: error: sample() in SuperTest cannot override sample() in Demo
public void sample() throws IOException {
^
overridden method does not throw IOException
1 error
D:\>javac Test.java
Test.java:20: error: unreported exception IOException; must be caught or declared to be thrown
obj.sample();
^
1 error