首頁>Club>
13
回覆列表
  • 1 # 影片好笑

    如果你知道你寫的某個函式有可能丟擲異常,而你又不想在這個函式中對異常進行處理,只是想把它丟擲去讓呼叫這個函式的上級呼叫函式進行處理,那麼有兩種方式可供選擇:第一種方式:直接在函式頭中throws SomeException,函式體中不需要try/catch。比如將最開始的例子中的testEx2改為下面的方式,那麼testEx1就能捕捉到testEx2丟擲的異常了。boolean testEx2() throws Exception{boolean ret = true;int b=12;int c;for (int i=2;i>=-2;i--){c=b/i;System.out.println("i="+i);}return true; }第二種方式:使用try/catch,在catch中進行一定的處理之後(如果有必要的話)丟擲某種異常。例如上面的testEx2改為下面的方式,testEx1也能捕獲到它丟擲的異常: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 (Exception e){System.out.println("testEx2, catch exception");Throw e;}}第三種方法:使用try/catch/finally,在catch中進行一定的處理之後(如果有必要的話)丟擲某種異常。例如上面的testEx2改為下面的方式,testEx1也能捕獲到它丟擲的異常: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);throw new Exception("aaa");}return true;}catch (java.lang.ArithmeticException e){System.out.println("testEx2, catch exception");

  • 中秋節和大豐收的關聯?
  • 戴森吹風機哪裡生產?