亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

try中有一個異常語句,后面只跟了一個finally, 返回上一級的時候為什么捕捉不到異常?

package com.imooc;


import javax.xml.transform.TransformerException;






public class TestException { ?

? ? public TestException() { ?

? ? } ?

??

? ? boolean testEx() throws Exception { ?

? ? ? ? boolean ret = true; ?

? ? ? ? try { ?

? ? ? ? ? ? ret = testEx1(); ?

? ? ? ? } catch (Exception e) { ?

? ? ? ? ? ? System.out.println("testEx, catch exception"); ?

? ? ? ? ? ? ret = false; ?

? ? ? ? ? ? throw e; ?

? ? ? ? } finally { ?

? ? ? ? ? ? System.out.println("testEx, finally; return value=" + ret); ?

? ? ? ? ? ? return ret; ?

? ? ? ? } ?

? ? } ?

??

? ? boolean testEx1() throws Exception { ?

? ? ? ? boolean ret = true; ?

? ? ? ? try { ?

? ? ? ? ? ? ret = testEx2(); ?

? ? ? ? ? ? System.out.println("ret=="+ret);

? ? ? ? ? ? //System.out.println("echang=="+e);

? ? ? ? ? ? if (!ret) { ?

? ? ? ? ? ? ? ? return false; ?

? ? ? ? ? ? } ?

? ? ? ? ? ? System.out.println("testEx1, at the end of try"); ?

? ? ? ? ? ? return ret; ?

? ? ? ? } catch (Exception e) { ?

? ? ? ? ? ? System.out.println("testEx1游戲場, catch exception"); ?

? ? ? ? ? ? ret = false; ?

? ? ? ? ? ? throw e; ?

? ? ? ? } finally { ?

? ? ? ? //System.out.println("異常是");

? ? ? ? ? ? System.out.println("testEx1, finally; return value=" + ret); ?

? ? ? ? ? ? return ret; ?

? ? ? ? } ?

? ? } ?

??

? ? boolean testEx2() throws Exception{ ?

? ? ? ? boolean ret = true; ?

? ? ? ? try { ?

? ? ? ? ? ? int b = 12; ?

? ? ? ? ? ? int c; ?

? ? ? ? ? ? for (int i = 2; i >= -2; i--) { ?

? ? ? ? ? ? ? ? c = b / i; ?

? ? ? ? ? ? ? ? System.out.println("i=" + i); ?

? ? ? ? ? ? } ?

? ? ? ? ? ? return true; ?

? ? ? ? } /*catch (NullPointerException e) { ?

? ? ? ? ? ? System.out.println("testEx2低級異常, catch exception"); ?

? ? ? ? ? ? ret = false; ?

? ? ? ? ? ? //System.out.println("e=="+e);

? ? ? ? ? ? throw e; ?

? ? ? ? ? ? //System.out.println("能不能執行?");

? ? ? ? } */finally { ?

? ? ? ? ? ? System.out.println("testEx2低級最終要執行, finally; return value=" + ret); ?


? ? ? ? ? ? return ret; ?

? ? ? ? } ?

? ? } ?

??

? ? public static void main(String[] args) { ?

? ?

? ? ? ? TestException testException1 = new TestException(); ?

? ? ? ? try { ?

? ? ? ? ? ? testException1.testEx(); ?

? ? ? ? } catch (Exception e) { ?

? ? ? ? ? ? e.printStackTrace(); ?

? ? ? ? } ?

? ? }?

}


正在回答

2 回答

testEx2()會出異常,但是你把catch注釋了,它當然捕獲不到,而且因為這是非檢查異常,所以系統不會自動拋出,所以定義testEx2() 時后面的throws Exception等于沒起到作用,也即上一級的testEx1()和testEx()都不會捕獲到異常

1 回復 有任何疑惑可以回復我~
#1

ziom

題主如果要采納我,請明天,今天我的采納滿了
2017-02-08 回復 有任何疑惑可以回復我~
#2

Deligence 提問者

非常感謝!
2017-02-13 回復 有任何疑惑可以回復我~

main函數里好像沒有執行testEx2()...

0 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消

try中有一個異常語句,后面只跟了一個finally, 返回上一級的時候為什么捕捉不到異常?

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號