2017-07-18 162 views
-2

背景

我正在拋光我的Java版本,準備參加Oracle Java 8考試,並且遇到了一些令人費解的問題。我有一些基本的東西就是這樣,它假定將作爲參數的兩個值傳遞:這拋出了哪個異常?

public static void main(String[] args) { 
    try { 
     String val1 = args[0]; 
     String val2 = args[1]; 
     ... 
    } catch (Exception e) { // <-- Here is where it gets tricky 
     ... 
    } 
} 

我意識到這是不好的形式趕上Exception,但是,當我通過在壞數據,我獲得兩個不同的具體例外情況,這取決於我對通用對象所做的操作,所以我不知道我需要在這裏捕捉哪些內容。

設置

如果我這樣做:

} catch (Exception e) { 
    System.err.println(e.toString()); 
} 

我得到一個java.lang.ArrayIndexOutOfBoundsException,這是有道理的,因爲args是一個數組。

但是,如果我這樣做,而不是:

} catch (Exception e) { 
    System.err.println(e.getCause().getMessage()); 
} 

我得到一個java.lang.NullPointerException 這也有道理,因爲有一個String對象的引用在 args是不是有 這不有意義了,因爲應該是是一個原因。

問題

哪些異常應該在這裏拋出?

+0

這可能會拋出一個ArrayIndexOutOfBoundsException,因爲您可能沒有傳遞足夠的參數 – ZeldaZach

+0

由於e.getCause()爲空,您可能會得到一個新的'NullPointerException'。 – khelwood

+0

@Chris不,忘記'Integer.parseInt()'部分。當我不給程序任何參數時是個例外。我會編輯出來,以顯示我真正要求的。 –

回答

1

嘗試修改該方法如下面和調試,一步一步: -

public static void main(String[] args) { 
    try { 
     String val1 = args[0]; 
     String val2 = args[1]; 
    } catch (Exception e) { // <-- Here is where it gets tricky 
     System.err.println(e.toString()); 
     Throwable thr = e.getCause(); 
     String msg = thr.getMessage(); 
     System.err.println(msg); 
    } 
} 

從try子句引發的唯一的例外是ArrayIndexOutOfBoundsException異常。

在catch子句中,您會發現e.getCause()返回null,因爲ArrayIndexOutOfBoundsException沒有其他因果異常。

因此,當您嘗試在空原因上調用getMessage()時,您將得到NullPointerException。