คำตอบคือ ไม่ได้ หากเมธอดของ Superclass โยน Exception ตัวหนึ่ง เมธอดใน Subclass ที่ Override ห้ามโยน Exception ที่เป็น Supertype (Parent Class) ของ Exception นั้น จะเกิด Compile-time Error ทันที
ตัวอย่างที่ทำให้เกิด Error
import java.io.FileNotFoundException;
import java.io.IOException;
abstract class Super {
public String readFile(String path) throws FileNotFoundException {
throw new FileNotFoundException();
}
}
public class ExceptionsExample extends Super {
@Override
// IOException เป็น Supertype ของ FileNotFoundException -> ผิดกฎ
public String readFile(String path) throws IOException {
// method body ......
}
}
Compile-time Error
ExceptionsExample.java:13: error: readFile(String) in ExceptionsExample cannot override readFile(String) in Super
public String readFile(String path)throws IOException {
^
overridden method does not throw IOException
1 error
เหตุผล
หากอนุญาตให้โยน Supertype ไปได้ โค้ดที่เรียกใช้ผ่าน Reference ของ Superclass (ซึ่งคาดหวังแค่ FileNotFoundException) จะไม่สามารถจับ IOException ที่กว้างกว่าได้ ทำให้โปรแกรมอาจล้มเหลวในขณะรันไทม์ Java จึงบังคับกฎนี้เพื่อความปลอดภัยของ Type System
สรุปกฎ Exception ใน Overriding
- โยน Exception ชนิดเดียวกัน ได้
- โยน Exception ที่เป็น Subtype (ลูก) ได้
- ห้ามโยน Supertype (พ่อแม่)
- ไม่โยน Exception เลย ก็ได้