Nếu phương thức của lớp cha ném một exception, phương thức ở lớp con không được phép ném super-type (lớp cha) của exception đó.
Ví dụ minh họa
Trong ví dụ sau, phương thức readFile() của lớp cha ném FileNotFoundException, nhưng phương thức ghi đè ở lớp con ném IOException - là super-type của FileNotFoundException.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super {
public String readFile(String path) throws FileNotFoundException {
throw new FileNotFoundException();
}
}
public class ExceptionsExample extends Super {
@Override
public String readFile(String path) throws IOException {
// method body ......
}
}
Lỗi biên dịch
Khi biên dịch, chương trình báo lỗi sau:
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
Quy tắc ghi nhớ: Khi override, exception ném ra phải là cùng kiểu hoặc sub-type (con) của exception ở phương thức cha. Không được ném super-type.