請(qǐng)問(wèn)test2() throw 的RuntimeException 為什么不需要test2() throws Exception 聲明拋出異常?
請(qǐng)問(wèn)test2() throw 的RuntimeException 為什么不需要test2() throws Exception 聲明拋出異常?
public void test1() throws DrunkException{
????throw new DrunkException("喝車別開(kāi)酒!");
}
public void test2(){
????try {
????????test1();
????} catch (DrunkException e) {
????// TODO Auto-generated catch block
????RuntimeException newExc =?
????????new RuntimeException(e);
????????// newExc.initCause(e);
????????throw newExc;
????}
}
2015-01-07
哦,不好意思,沒(méi)看到是RuntimeException,該異常屬于Java中的特例,因?yàn)榫幾g器沒(méi)有在這個(gè)問(wèn)題上對(duì)異常說(shuō)明進(jìn)行強(qiáng)制檢查,RuntimeException類型的異常也許會(huì)穿越所有的執(zhí)行路徑達(dá)到main方法中,而不會(huì)被捕獲。對(duì)于該異常類,編譯器不需要異常說(shuō)明,其輸出會(huì)直接報(bào)告給System.err,如果說(shuō)RuntimeException在到達(dá)main方法之前沒(méi)有被捕獲,那么在退出當(dāng)前程序的時(shí)候,會(huì)直接調(diào)用printStackTrace()方法。
你可以把這個(gè)異常理解為編程錯(cuò)誤,所以不用拋出也是可以的
2015-01-07
參看1-1的視頻,我想是因?yàn)镽untimeException 屬于unchecked exception,?對(duì)于RuntimeException,java編譯器不要求把它捕獲或者拋出
2015-01-07
test2不是有try-catch語(yǔ)句塊嗎?這個(gè)語(yǔ)句塊就是捕獲異常使用的,所以當(dāng)有這個(gè)語(yǔ)句塊的時(shí)候就不用拋出異常了,你可以把test1和test2對(duì)比一下,test1中是直接拋出的異常沒(méi)有try-catch的使用