2014-12-02 29 views
1

考慮以下代碼:超類型和子類型的異常處理

public class CheckException 
{ 
    public static void main(String [] args) 
    {  
     int a = 10; 
     try{ 
      int c = a/0; 
     } catch(Exception e){ 

     } catch(ArithmeticException e1){ \\ compilation error 

     } 
    } 
} 

我懷疑是在第二抓生成編譯錯誤,因爲它已經被超類型的異常處理。但是爲什麼當第二個catch塊到達第一個位置並且第一個到達第二個位置時(如下圖),編譯錯誤不會發生?

public class CheckException { 

public static void main(String [] args){ 

    int a = 10; 
    try{ 
     int c = a/0; 
    } catch(ArithmeticException e){ 
//  System.out.println("1"); 
    } 
    catch(Exception e1){ 
//   System.out.println("2"); 
    } 
} 

} 

然後,第一個塊(即ArithmeticException)也會在它到達catch(Exception e)之前處理異常。

修改

現在,我將所有的unchecked異常趕上(例外五)前。

public class CheckException { 

public static void main(String [] args){ 

    int a = 10; 
    try{ 
     int c = a/0; 
    } catch(ArithmeticException e){ 
    System.out.println("1"); 
    } 
    catch(ArrayIndexOutOfBoundsException e1){ 
     System.out.println("2"); 
    } 
    catch(ClassCastException e1){ 
     System.out.println("2"); 
    } 
    catch(IllegalArgumentException e1){ 
     System.out.println("2"); 
    } 
    catch(IllegalStateException e1){ 
     System.out.println("2"); 
    } 
    catch(NullPointerException e1){ 
     System.out.println("2"); 
    } 
    catch(AssertionError e1){ 
     System.out.println("2"); 
    } 
    catch(ExceptionInInitializerError e1){ 
     System.out.println("2"); 
    } 
    catch(StackOverflowError e1){ 
     System.out.println("2"); 
    } 
    catch(NoClassDefFoundError e1){ 
     System.out.println("2"); 
    } 
    catch(ArrayStoreException e1){ 
     System.out.println("2"); 
    } 
    catch(IllegalMonitorStateException e1){ 
     System.out.println("2"); 
    } 
    catch(IndexOutOfBoundsException e1){ 
     System.out.println("2"); 
    } 
    catch(NegativeArraySizeException e1){ 
     System.out.println("2"); 
    } 
    catch(SecurityException e1){ 
     System.out.println("2"); 
    } 
    catch(UnsupportedOperationException e1){ 
     System.out.println("2"); 
    } 
    catch(Exception e1){ 
     System.out.println("2"); 
    } 
} 

} 

現在,所有的unchecked異常越來越深遠趕上(例外五)前處理。那麼,除了這些之外,是否還有未經檢查的異常,因爲沒有生成編譯錯誤?或者是別的什麼?

+3

因爲除ArithmeticException以外,還有未經檢查的Exception。 – 2014-12-02 10:50:30

+0

您不需要爲try塊內的邏輯設置第二個catch塊。僅當拋出ArithmeticException以外的其他控制塊(Exception)時才進入第二個catch塊(Exception)。因此,你仍然可以寫第二個catch塊,這完全沒有問題。 – hemanth 2014-12-02 10:59:10

+0

@MarkoTopolnik如果我在最後一個塊之前添加所有未經檢查的異常,該怎麼辦?它會一樣嗎? – Leo 2014-12-02 11:36:48

回答

1

更具體的例外 - ArithmeticException - 應該是第一位的,因爲它允許您以不同的方式處理它,然後處理Exception的一般處理。

如果你把異常處理程序或Exception第一,你做的ArithmeticException死代碼的處理程序,因爲它永遠不能達到 - 任何ArithmeticException將通過Exception的處理程序捕獲。

4

在Java中,catch塊按它們在源文件中出現的順序觸發。

因此,如果更一般的Exception最先出現,它也會觸發,如果一個ArithmeticException被拋出,並且第二個catch塊是不可達的。

在另一方面,如果更具體ArithmeticException catch塊是第一位的,然後爲Exception catch塊不會成爲不可訪問,因爲有沒有被第一塊捕獲的Exception子類。

相關問題