例一,當類B繼承類A時:
class A{
public void show() throws FileNotFoundException{
BufferedInputStream in=new BufferedInputStream(new FileInputStream("ad.dat"));
}
}
class B extends A{
public void show() throws FileNotFoundException, SQLException{
BufferedInputStream in=new BufferedInputStream(new FileInputStream("ad.dat"));
Connection conn=JdbcUtils.getConnection();
}
}
編譯時會提示錯誤,原因,B中的show方法拋出的異常中SQLException在其父類A中並沒有拋出
例二,當類D實現接口C時:
interface C{
void disply();
}
class D implements C{
public void disply() throws FileNotFoundException{
BufferedInputStream in=new BufferedInputStream(new FileInputStream("ad.dat"));
}
}
編譯時同樣會提示錯誤,原因是D中的display方法拋出了FileNotFoundException異常,而在其實現的接口C中聲明的display方法沒有拋出任何異常。
總結:
某個類實現了一個接口或繼承了一個類,當該類進行方法覆蓋時,拋出的異常只能是原方法的異常或者是原方法異常的子集。