2
請在下面找到我的代碼,我想清除我的概念與拋出異常重寫。下面會提供代碼工作,如果是,那麼爲什麼。?我問這個問題是因爲IOException和ArithmeticException之間沒有直接的父子關係。重寫時父子層次對拋出重要。
public class TestExceptionChild {
public static void main(String[] args) {
Parent parent = new Child();
try {
parent.msg();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Parent{
void msg() throws IOException{
System.out.println("parent");
}
}
class Child extends Parent{
void msg() throws ArithmeticException{
System.out.println("child");
}
}
儘管IOException不是'RuntimeException'。爲什麼overriden方法不需要'throws IOException'呢?它怎麼會拋出* nothing *,但不會拋出另一種檢查的異常? – Gendarme
@Gendarme你可以把「throws nothing」看作拋出IOException的一個子集。然而,反過來並不正確。如果父項不拋出,重寫的子項不能拋出檢查的異常。 – pathfinderelite
當然。我應該已經意識到了。 – Gendarme