(1)異常的限制
當覆蓋方法的時候,只能丟擲在基類方法的異常說明裡列出的那些異常。這個限制很有用,因為這意味著,當基類使用的**應用到期派生類物件的時候,一樣能夠工作。
public class exceptionrestrictiontest extends inning implements storm
//普通方法必須與基類保持一致,基類沒有丟擲異常,則覆蓋的方法也不能丟擲異常
//public void walk() throws popfoul{}
//介面不能新增新的exception到基類中已經存在的方法
//public void event()throws baseballexception,rainedout{}
//如果介面中的方法在基類中不存在,那麼介面可以新增exception
public void rainhard() throws rainedout{}
//可以選擇不丟擲基類方法丟擲的異常
public void event(){}
//覆蓋的方法可以丟擲基類方法丟擲的異常的子類
public void atbat() throws popfoul{}
public static void main(string args)
catch(popfoul e)
catch(rainedout e)
catch(baseballexception e)
//不用捕獲基類atbat()方法丟擲的異常
trycatch(strike e)
catch(foul e)
catch(rainedout e)
catch(baseballexception e)
} }class baseballexception extends exception{}
class foul extends baseballexception{}
class strike extends baseballexception{}
abstract class inning
public void event() throws baseballexception{}
public abstract void atbat() throws strike,foul;
public void walk(){}
}class stormexception extends exception{}
class rainedout extends stormexception{}
class popfoul extends foul{}
inte***ce storm
(2)構造器與異常
對於在構造階段會丟擲的異常,並且要求清理的類,最安全的使用方式是使用巢狀的try字句。
這種通用的清理慣用法在構造器不丟擲任何異常時也應該運用,其基本規則是:在建立了需要清理的物件之後,立即進入try-finally語句塊,並在finally字句下進行清理工作。
class needscleanup
}class constructionexception extends exception{}
class needscleanup2 extends needscleanup; }
public class cleanup
finally
//section 2:
//如果構造器會丟擲異常,則必須使用巢狀層次捕獲構造的異常
tryfinally
}catch (constructionexception e)
}finally
}catch(constructionexception e)
}}
Java學習筆記 異常
在程式編寫中,難免會產生異常,這時候就需要對異常進行處理 異常的體系 throwable error exception exception和error的子類名都是以父類名作為字尾 try catch 異常類 變數 finally try catch exception e try finally ...
java學習筆記 java異常處理
1.異常的處理流程 建立異常 丟擲異常 捕獲處理異常 對應於 try throw catch try throw.catch 要點 宣告乙個異常 public void mymethod throws exception1,exception2,exception3,使用throw 來宣告乙個方法的...
java學習筆記之異常
基礎的就不多說了,說一下容易被忽略的知識點。a 不管有木有出現異常,finally塊中 都會執行 b 當try和catch中有return時,finally仍然會執行 c finally是在return後面的表示式運算後執行的 此時並沒有返回運算後的值,而是先把要返回的值儲存起來,管finally中...