Throwing exception problem about subclass overriding parent class in Java

  • 2021-07-18 07:51:23
  • OfStack

Java subclass overrides the parent class method and cannot throw more exceptions than the parent class, which is not accurate enough.

The exact 1 point is described as:

Exception types thrown by subclasses cannot be broader than those thrown by parent classes. Assuming that the parent class throws an exception ParentException, and the other two subclasses inherit from ParentException, which are ChildException1 and ChildException2 respectively, then the subclasses can throw exceptions ChildException1 and ChildException2 at the same time. Meet the 1 condition that "the exception types thrown by subclasses cannot be broader than those thrown by the parent class".

Note:

Subclasses can also choose not to throw any exceptions, even if they are exceptions defined by the parent class.

Why Java is designed like this, let's give an example to analyze:


package exceptions;
class Sick extends Exception{}
class FeverSick extends Sick{}
class JointSick extends Sick{}
class Children extends People{
 public void coldAir() throws FeverSick{ }
}
class Adults extends People{
  public void coldAir(){}
}
class Olds extends People{
  public void coldAir() throws JointSick{ }
}
public class People {
 public void coldAir() throws Sick{ }
}

As in the above code, 1 parent class is defined People Class, and its three subclasses Children , Adults , Olds Assuming there is a cold air event in the parent class, it throws an exception of type Sick. However, because the three subclasses have different abilities to resist diseases, Adults class may not throw exceptions because of its strong resistance. However, Children and Adults may throw out different subtypes of Sick because of their weak resistance. However, it should be noted that subclasses cannot throw exception types that are completely unrelated to the Sick class, such as the height Height type. Because the parent class must be regarded as a major premise, its subclasses cannot throw exceptions that are more out of line than the parent class exceptions, otherwise they cannot be recognized.

That's probably what it means.

Summarize


Related articles: