2016-11-06 32 views
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"); 
    } 
} 

回答

1

這是可行的,但僅僅是因爲ArithmeticException延伸RuntimeException(即它不是一個檢查異常,所以使用throws條款這裏是不必要的)。如果不是ArithmeticException,而是使用檢查的異常,則它必須是IOException或擴展類型IOException。否則,你會得到一個編譯錯誤。

所以要回答你的問題,是的,層次結構是重要的檢查例外。有關更多詳情,請參閱here

+1

儘管IOException不是'RuntimeException'。爲什麼overriden方法不需要'throws IOException'呢?它怎麼會拋出* nothing *,但不會拋出另一種檢查的異常? – Gendarme

+0

@Gendarme你可以把「throws nothing」看作拋出IOException的一個子集。然而,反過來並不正確。如果父項不拋出,重寫的子項不能拋出檢查的異常。 – pathfinderelite

+0

當然。我應該已經意識到了。 – Gendarme