在Java中,关于方法覆盖,异常处理的规则是什么?
当覆盖超类方法时,如果该方法抛出异常,您需要遵循一定的规则。
应该抛出相同的异常或者子类型
如果超类方法抛出某个异常,子类中的方法应该抛出相同的异常或者它的子类型。
示例
在下面的示例中,超类的readFile()方法抛出了IOException异常,而子类的readFile()方法抛出了FileNotFoundException异常。
由于FileNotFoundException异常是IOException的子类型,所以该程序可以在没有任何错误的情况下编译和执行。
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 IOException { throw new IOException(); } } public class ExceptionsExample extends Super { @Override public String readFile(String path) throws FileNotFoundException { Scanner sc = new Scanner(new File("E://test//sample.txt")); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(" "+input); } return sb.toString(); } public static void main(String args[]) { String path = "E://test//sample.txt"; ExceptionsExample obj = new ExceptionsExample(); try { System.out.println(obj.readFile(path)); }catch(FileNotFoundException e) { System.out.println("Make sure the specified file exists"); } } }登录后复制