java 向上抛异常_java throws 向上抛出的概念问题
展開全部
------------------附注------------------------
向上拋出的意思?針對? 子類?父類,
這里面涉及到幾個方面,最重32313133353236313431303231363533e4b893e5b19e31333332613637要的一點,
(先拋子類的異常,再拋父類的異常.)(FALSE)
如果在該方法寫明catch子句,catch的順序是子類異常,后是父類異常.
若在子類異常中捕獲了,則不用向父類(也就是您講的上一級)拋出,所有的異常都有基類java.lang.Throwable,也可自定義,多用于業務層面.
什么時候使用throws?
在基礎方法可能產生的異常使用throws,在應用方法的地方捕獲異常處理。
如果在每層基礎方法處捕獲異常,那么在應用方法處很可能會忽略掉下層基礎方法處理出的null。所以更好的方式是讓基礎方法throws異常以提醒調用它的應用方法捕獲并處理它。
何時使用throw?
在需要最終處理一些事件的地方,例如:
public?ResultSet?query(String?sql)?throws?NullPointerException,SQLException?{
try?{
conn?=?pool.getConnection();
pstmt?=?conn.prepareStatement(sql);
rs?=?pstmt.executeQuery();
}?catch?(NullPointerException?e)?{
thorw?new?NullPointerException();?//?在此拋出的null異常可以不用在方法后面throws;且此異常出現一定會被捕獲到;
}?catch?(SQLException?e)?{
throw?new?SQLException();
}?finally?{
pool.releaseConnection(conn);
}
return?rs;
}
這里為了finally釋放連接,捕獲了異常,但是并不想在基礎類的地方處理它,所以重新拋出,讓調用它的應用方法可以注意到并判斷處理。
特殊的Exception:NullPointerException。
NullPointerException在被拋出后可以不用throws也可被調用的方法捕獲到。見上例注釋。
***********************jmuok2013-4-7?00:26***********************************public class TestException{
public static void main(String[] args){
throw new FatherException();
// throw new ChildException();
// 比較兩者區別.
}
}
class FatherException extends RuntimeException{
public FatherException(){
System.out.println("My name is father exception....");
}
}
class ChildException extends FatherException {
public ChildException() {
System.out.println("My name is child exception....");
}
}
--throw new FatherException();--------result---------
Exception in thread "main" My name is father exception....
com.monical.FatherException
at com.monical.TestException.main(TestException.java:5)
--throw new ChildException();---------result---------
My name is father exception....
My name is child exception....
Exception in thread "main" com.monical.ChildException
at com.monical.TestException.main(TestException.java:6)
總結
以上是生活随笔為你收集整理的java 向上抛异常_java throws 向上抛出的概念问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 快手怎么开启账号保护
- 下一篇: 快手如何设置私密账号