当您尝试处理由特定方法引发的异常(已检查)时,您需要使用Exception类或发生了Exception的超类来捕获它。
以同样的方式覆盖超类的方法,如果它抛出异常-
子类中的方法应引发相同的异常或其子类型。
子类中的方法不应抛出其父类型。
您可以覆盖它而不会引发任何异常。
如果在继承(继承)中有三个名为Demo,SuperTest和Super的类,则如果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