2013-10-04 62 views
0

當我的主類拋出一個檢查的異常,不應該覆蓋的方法也應該實現檢查的異常??檢查異常覆蓋java

class Master{ 
    String doFileStuff() throws FileNotFoundException{ 
     return "a"; 
    } 
} 

public class test extends Master{ 

    public static void main(String[] args){ 
    } 


    String doFileStuff(){ 
     return "a"; 
    } 

} 
+0

確保將'@ Override'註釋添加到'test.doFileStuff()'。 –

+3

nope。如果你不會扔它 - 你可以跳過它。但是您不允許添加其他已檢查的異常。 – Admit

+0

[未經檢查的異常 - 爭議](http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html) – Husam

回答

0

覆蓋方法應保留相同的合同。

基本上,這意味着它可以拋出FileNotFoundExceptionFileNotFoundException的子類列表,但它不必。

檢查這個例子:

Master a = new test(); 
a.doFileStuff(); //this line might throw an exception, and you should catch it. 
       //but it is not illegal for test class not to throw an exception 

現在,我們可以做同樣的事情的FileNotFoundException一個子類,比FileNotFoundException不同的另一些例外同樣的事情。對於後面這種情況,我們將看到我們的代碼甚至不會編譯,因爲test類中的doFileStuff方法會拋出與FileNotFoundException不同的已檢查異常。

0

覆蓋方法時,你可以聲明所有異常,異常的一個子集,或者沒有通過超類的方法拋出的異常。您也可以聲明任何異常,這是由超類方法聲明的異常的子類。

你可能不會拋出不是由超類的方法聲明任何異常,除非它是由父類方法聲明的異常的子類。

0

不是真的,只是在代碼中顯示的評論承認的原因

異常可當你真正擁有讓他們的風險被拋出,如果你有地方在你的代碼throw new FileNotFoundException();你不得不添加一試趕上或拋出異常。然而,如果你壓倒一切,那麼你可以消除威脅,如果你增加了一些新的風險,那麼你必須用新方法來處理它們。

import java.io.FileNotFoundException; 

class Master { 
    String doFileStuff() throws FileNotFoundException { 
    throw new FileNotFoundException(); // it always throws an exception. 
    } 
} 

public class Test extends Master { 

    public static void main(String[] args) { 
    String a = new Test().doFileStuff(); 
    String b = new Master().doFileStuff(); 
    } 

    String doFileStuff() { 
    return "a"; //It always returns a. No risks here. 
    } 

} 
0

這是沒有必要爲一個壓倒一切的方法來重新申報所有Exception S按超類方法拋出。只需要它不會聲明Exception s被拋出,不是由超類方法拋出的

的JLS第8.4.8.3闡述:

更確切地說,假設B是一個類或接口,和A是 超類或B的超接口,和方法聲明n的乙 覆蓋或隱藏A.方法聲明米然後:

  • 如果n具有拋出提及任何檢查的異常類型子句, m必須有一個throws子句,或發生編譯時間錯誤。

  • 對於每一個檢查中所列出的異常類型拋出的n子句, 同一異​​常類或它的超類型必須發生在 擦除中的一個(§4.6)的拋出的米條款;否則,發生編譯時 錯誤。

  • 如果未擦除拋出的米子句中不包含的 的超類型每種類型的異常在拋出N,編譯時發生 未經檢查的警告的子句。

這很有道理。爲什麼應該子類方法可能會拋出相同的Exception s作爲它覆蓋的超類方法?這是有道理的,它不申報其他例外,因爲這會破壞這樣的場景:

public class Super 
{ 
    public void method() throws FooException {} 
} 

public class Sub extends Super { 
{ 
    public void method() throws FooException, BarException {} 
} 

然後使用變得模糊:

Super sup = new Sub(); 
try { 
    sup.method(); 
} 
// But the subclass could (if it were allowed here) 
// throw BarException! 
catch (FooException e) {}