[英]java - checked exception for 'throws' in overridden method
我正在使用java中的方法覆蓋來練習異常處理機制...我的代碼如下:
class base {
void show() {
System.out.println("in base class method");
}
}
class derived extends base {
void show() throws IOException {
System.out.println("in derived class method");
throw new IOException();
}
}
class my {
public static void main(String[] args) {
try {
base b = new derived();
b.show();
}
catch (IOException e) {
System.out.println("exception occurred at :" + e);
}
}
}
顯示錯誤:
所以,我更正了以下內容:
void show() throws IOException{
它工作正常......
我做了一個實驗:
void show() throws Exception{
但它也顯示錯誤:
據我了解,這是因為公司的覆蓋方法throws
條款應提及確切的檢查異常的throws
父類方法的條款。
與第二種情況一樣,如果我在throws子句中編寫IOException
的超類Exception
,它也會顯示錯誤。 為什么? 即使Exception
是所有異常的父類。
我剛試驗過...這個錯誤告訴我不知道......
任何人都可以解釋它說的內容以及在重寫方法的throws
子句中提到已檢查異常的限制是什么?
樣本中有兩個相關錯誤:
1)您的基類方法為派生類方法提供“模板”或基本標准 。
因此,基類應該聲明一個超集,即派生類的相同異常類或基類異常類。 您無法聲明它不會拋出任何內容,因為那時條件將不匹配。
所以如果你的派生類方法是這樣的:
class Derived extends Base {
void show() throws IOException {
//...
}
}
然后基類方法“必須”是:
class Base {
void show() throws /*Same or base classes of IOException*/ {
//...
}
}
所以這兩個工作:
class Base {
void show() throws Exception {
//...
}
}
要么
class Base {
void show() throws Throwable {
//...
}
}
2)當您嘗試上述操作時, show
方法的整體聲明現在變為throws Exception
。 因此,使用此show
任何人都必須捕獲該異常。
在main
方法中,您正在捕獲IOException
。 這將不再有效,編譯器抱怨“你好,你正在捕獲IOException,那么Exception的所有其他可能性呢?” 這是您顯示的第二個錯誤。
要解決此問題,請更改main
方法catch以包括在基類中聲明的Exception
:
class My {
public static void main(String[] args) {
try {
base b = new derived();
b.show();
}
/* NOTE: CHANGED FROM IOException TO Exception */
catch (Exception e) {
System.out.println("exception occurred at :" + e);
}
}
}
重寫方法在其throws
子句中可能只包含與超級方法相同的已檢查異常,或者最多只包含派生類型。
例如,如果你說
class Base {
public void foo(int y) throws IOException {
// ...
}
}
和
class Derived extends Base {
public void foo(int y) throws Exception {
// ...
}
}
然后你的編譯器會說Derived
中的foo
方法與其超類中的throws子句不兼容。
另一種方式是有效的,因為如果我說
class Base {
public void foo(int y) throws Exception {
// ...
}
}
和
class Derived extends Base {
public void foo(int y) throws IOException {
// ...
}
}
沒關系。
為什么。
考慮一下方法的用法。 Java希望您以多態方式使用該方法,例如
Base a = new Derived();
a.foo(3);
因此,編譯器將強制您捕獲foo
在您聲明的變量類型( Base
)中拋出的異常。 所以你的代碼將成為
Base a = new Derived();
try {
a.foo(3);
} catch (Exception e) {
// ...
}
因此,您在Derived
類型中聲明的Exception
的子類型可以使用上面的代碼( Exception
的catch也適用於它的任何子類型)因此,Java將允許您在派生中聲明IOException
,因為它以后不會再擔心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.