[英]exception handling in the implemented method
下面的代碼給出了一個檢查錯誤, throws Exception
:
import java.io.IOException;
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
@Override
public void ss99 () throws Exception {}
// ...
}
而下面的一個可以編譯:
import java.io.IOException;
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
@Override
public void ss99 () throws NullPointerException {}
// ...
}
Java在執行什么邏輯上有什么想法?
TIA。
throws
關鍵字指示方法或構造函數可以拋出異常,盡管不是必須的。
讓我們從第二個片段開始
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
@Override
public void ss99 () throws NullPointerException {}
}
考慮
some ref = getSome();
try {
ref.ss99();
} catch (IOException e) {
// handle
}
您需要使用的只是界面的some
。 我們(編譯器)不知道它所引用的對象的實際實現。 因此,我們必須確保處理可能引發的任何IOException
。
如果是
SQL2 ref = new SQL2();
ref.ss99();
您正在使用實際的實現。 此實現保證了它永遠不會拋出IOException
(通過不聲明它)。 因此,您不必處理它。 您也不必處理NullPointerException
因為它是未經檢查的異常。
關於您的第一個片段,略有變化
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
@Override
public void ss99 () throws Exception { throw new SQLException(); }
}
考慮
some ref = new SQL2();
try {
ref.ss99();
} catch (IOException e) {
// handle
}
因此,盡管您正在處理接口中聲明的異常,但是您將讓未經檢查的異常SQLException
逸出。 編譯器不允許這樣做。
必須聲明一個重寫的方法以引發相同的異常(作為父類)或其子類之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.