查看完整版本: 問題求解3
頁: [1]

1006910211 發表於 2016-6-17 08:50 PM

問題求解3


各位大大,請協助求解以下問題,感謝
我的疑問是,dispResult這個方法沒有使用throws Exception將例外物件傳給上一層,照理來說程式應該會終止        但實際結果卻可以跑出System.err.println("third exception");


public class Test {
        static void dispResult(int[] num) {
                try {
                        System.out.println(num / (num - num));
                } catch (ArithmeticException e) {
                        System.err.println("first exception");
                }
                System.out.println("Done");
        }

        public static void main(String[] args) {
                try {
                        int[] arr = {100, 100};
                        dispResult(arr);
                } catch (IllegalArgumentException e) {
                        System.err.println("second exception");
                } catch (Exception e) {
                        System.err.println("third exception");
                }
        }
}

...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div><div></div>

22616846 發表於 2016-6-17 11:18 PM

本帖最後由 22616846 於 2016-6-17 11:20 PM 編輯

因為 exception 你沒catch啊 , 他會發生ArrayIndexOutOfBoundsException ,因為你宣告的陣列長度為2 ,你應該要改成num / (num - num)才會發生ArithmeticException

1006910211 發表於 2016-6-17 11:47 PM

22616846 發表於 2016-6-17 11:18 PM static/image/common/back.gif
因為 exception 你沒catch啊 , 他會發生ArrayIndexOutOfBoundsException ,因為你宣告的陣列長度為2 ,你應 ...

因為沒有catch到所以例外物件沒有做處理,但此程式沒有throws Exception
static void dispResult(int[] num) throws Exception{...}
為何會將例外物件丟到主方法(main)做處理,謝謝...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div>

snowflying 發表於 2016-6-18 01:09 AM

1006910211 發表於 2016-6-17 11:47 PM static/image/common/back.gif
因為沒有catch到所以例外物件沒有做處理,但此程式沒有throws Exception
static void dispResult(int[] n ...

如果內層沒有處理掉,或者重新丟出例外
會一直往外層丟,直到有任何一層處理掉為止

該例外是 ArrayIndexOutOfBoundsException
dispResult 裡面的 catch 沒有一個能捕捉到
所以會由呼叫他的 main 處理
而 main 的 catch (Exception e) 能夠捕捉到
因為 ArrayIndexOutOfBoundsException 屬於 Exception 的子類別
就進入了那一部份
要是連 main 都沒有處理,就會得到
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div>

Dnight0729 發表於 2016-6-18 09:07 AM

Exception是Java最大的錯誤處理,會處理所有你沒處理到的Exception

所以會跑到第三個錯誤那邊<br><br><br><br><br><div></div>

sssun1986 發表於 2016-7-1 08:18 AM

不是說沒有throw Exception就不會拋例外@@
throws只是讓你決定何時要拋出,
預設的狀況就是沒有catch就會往上一層拋,
拋到系統為止就是系統接手處理印出stack trace了。
頁: [1]