Exception throwing rules when Java exception subclasses override parent class methods

When an exception is thrown by a parent class method, the subclass method overrides the exception rules.

  • The exception class thrown by the subclass method declaration should be smaller or equal to the exception class thrown by the parent class method declaration (or even not thrown)

class Fahter{
    
    
	
	public void method() throws RuntimeException  {
    
     }
}

// 三种情况
class Son extends Fahter{
    
    
	
	// public void method() { } // 不抛出异常
	
	// public void method() throws RuntimeException { } // 抛出与父类方法相同的异常
	
	public void method() throws ArrayIndexOutOfBoundsException {
    
     } // 抛出父类方法异常的子集
}

When the parent class method does not declare any exception, can the subclass method throw an exception when overriding it?

  • Yes, but subclasses can only declare to throw anyunchecked exceptions when overriding methods i.e.RuntimeException
class Animal{
    
    
	
	public void cry() {
    
     } // 不抛出任何异常
}

class Dog extends Animal{
    
    
	
	// public void cry() { } // 不抛出异常
	
	// public void cry() throws RuntimeException { } // 可抛出运行时异常
	
	// public void cry() throws ClassNotLoadedException { } // 编译报错 不能抛出受检异常
	
	// public void cry() throws Exception{ } // 编译报错 Exception包含受检异常
	
}

Guess you like

Origin blog.csdn.net/Klhz555/article/details/134253299