When the subclass overrides the parent class method, no more checked exceptions can be thrown

When I read "Java Concurrency in Practice", I noticed a sentence:

Runnable is a fairly limiting abstraction; run cannot return a value or throw checked exceptions

Success aroused my curiosity. Why can't Runnable's run method throw a checked exception? Let's first look at the code of the Runnable class:

public interface Runnable {
    
    
    public abstract void run();
}

It can be seen that the definition of its run method confirms that no exception is thrown. Do another experiment to verify it. The program is as follows. It can be compiled, and RuntimeException will be reported at runtime, but if the thrown RuntimeException is replaced with a checked exception, such as IOException, it will not be compiled:

abstract class AClass {
    
    
    public static void main(String[] args){
    
    
       Runnable r = new Runnable() {
    
    
           public void run() throws RuntimeException{
    
    
                throw new RuntimeException("rr");
           }
       };
       new Thread(r).start();
    }
}

In order to find a general rule, another experiment was done:

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() throws RuntimeException/*,Exception ,IOException */{
    
    }
}

class Olds extends People{
    
    
    public void coldAir() throws JointSick{
    
     }
}

public class People {
    
    
    public void coldAir() throws Sick {
    
     }
}

The conclusion is as follows: When a subclass overrides a parent method, if checked exceptions are thrown, the Exception must be a subclass (or similar) of the Exception thrown by the parent method. RuntimeException is not subject to this restriction.

Guess you like

Origin blog.csdn.net/qq_23204557/article/details/112148050