展开全部
------------------附注------------------------
向上抛出的意思 针对 子类 父类,
这里面涉及到几个方面,最重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)