簡體   English   中英

Checked Exception覆蓋Java

[英]Checked Exception overrides java

當我的Master類拋出一個檢查異常時,override方法是否也應該實現該檢查異常?

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

public class test extends Master{

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


    String doFileStuff(){
        return "a";
    }

}   

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

基本上,這意味着它可以拋出一個FileNotFoundException或子類列表FileNotFoundException ,但它不就得了。

檢查以下示例:

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檢查異常是非法的。

覆蓋方法時,可以聲明所有異常,異常的子集或超類方法未引發的所有異常。 您也可以聲明任何超類方法聲明的異常的子類。

除非它是超類方法聲明的異常的子類,否則您不能拋出任何未由超類方法聲明的異常。

不完全是,只是為了在代碼中顯示Admit注釋的原因

當您確實有獲取異常的風險時,如果您在代碼中的某個地方throw new FileNotFoundException(); ,則可能throw new FileNotFoundException(); 您被迫添加try catch或引發異常。 但是,如果您要覆蓋,則可以消除威脅,如果添加了一些新風險,則必須使用新方法來處理它們。

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.
  }

}

重寫方法不必重新聲明超類方法引發的所有Exception 它沒有聲明這只是必要的Exception s到拋出不是由超類方法拋出。

JLS的8.4.8.3節詳細說明:

更准確地說,假設B是類或接口,而A是B的超類或超接口,並且B中的方法聲明n覆蓋或隱藏A中的方法聲明m。然后:

  • 如果n具有引發任何檢查過的異常類型的throws子句,則m必須具有throws子句,否則會發生編譯時錯誤。

  • 對於n的throws子句中列出的每個檢查的異常類型,必須在m的throws子句的擦除(第4.6節)中出現相同的異常類或其超類之一; 否則,將發生編譯時錯誤。

  • 如果m的未擦除throws子句在n的throws子句中不包含每種異常類型的超類型,則會發生編譯時未檢查的警告。

那講得通。 為什么一個子類方法可能拋出同樣的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) {}  

在子類中是可選的,請檢查以下鏈接:

http://www.tutorialspoint.com/java/java_overriding.htm

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM