2012-07-18 35 views
2

我想使用try-catch塊來處理兩種情況:特定的異常和其他異常。我可以這樣做嗎? (示例)Try-catch short-circuit/fall-through java

try{ 
    Integer.parseInt(args[1]) 
} 

catch (NumberFormatException e){ 
    // Catch a number format exception and handle the argument as a string  
} 

catch (Exception e){ 
    // Catch all other exceptions and do something else. In this case 
    // we may get an IndexOutOfBoundsException. 
    // We specifically don't want to handle NumberFormatException here  
} 

NumberFormatException是否也會由底部塊處理?

+1

難道你只是試試嗎? – 2012-07-18 01:58:37

+1

是的,我可以,但是這對其他人也是有用的,我希望。此外,davidbuzatto的加入也揭示了一個我不知道的特徵,所以通過這個問題我獲得了更多的信息,而不是通過一個簡單的測試。 – 2012-07-18 02:02:13

回答

8

不,因爲更具體的異常(NumberFormatException)將在第一個catch中處理。重要的是要注意,如果你交換緩存,你將得到一個編譯錯誤,因爲你必須在更一般的異常之前指定更具體的異常。

這不是你的情況,但由於Java 7中你可以捕捉組的異常,如:

try { 
    // code that can throw exceptions... 
} catch (Exception1 | Exception2 | ExceptionN exc) { 
    // you can handle Exception1, 2 and N in the same way here 
} catch (Exception exc) { 
    // here you handle the rest 
} 
4

如果一個NumberFormatException被拋出,它將被第一個catch捕獲,第二個catch將不會被執行。所有其他例外都轉到第二個例外。

0

嘗試這樣的:NFE捕獲新增throw new Exception()

try{ 
    Integer.parseInt(args[1]) 
} 

catch (NumberFormatException e){ 
    // Catch a number format exception and handle the argument as a string 
    throw new Exception();  
} 

catch (Exception e){ 
    // Catch all other exceptions and do something else. In this case 
    // we may get an IndexOutOfBoundsException. 
    // We specifically don't want to handle NumberFormatException here  
} 

通過這種方式,你可以在它的catch塊處理NFE。而在另一個塊中的所有其他。您不需要在第二個區塊中再次處理NFE