Exception three child parent exception

Sub-parent exception

  • If the parent class throws multiple exceptions, when the subclass overrides the parent class method, it will throw the same exception as the parent class or a subclass of the parent class exception or no exception will be thrown
  • The method of the parent class does not throw an exception, and the child class cannot throw an exception when it overrides the method of the parent class. At this time, the child class generates the exception and can only be caught and processed, and cannot be declared to be thrown.

Code example

public class Demo09FuZI {
 public void show01()throws NullPointerException,ClassCastException{};
public void show02()throws IndexOutOfBoundsException{};
public void show03()throws IndexOutOfBoundsException{};
public void show04(){};

}
class Zi extends Demo09FuZI{
//1.抛出相同的异常
@Override
public void show01()throws NullPointerException,ClassCastException{};
//2.抛出父类异常的子类

@Override
public void show02() throws ArrayIndexOutOfBoundsException {

}
//3.子类重写方法时,不抛出异常

@Override
public void show03() {

}
//父类方法没有抛出异常,子类重写父类该方法时也不可以抛出异常,此时子类产生该异常,只能捕获处理,不能声明抛出
@Override
public void show04() {
    try {
        throw new Exception("编译器异常");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/102543428