2013-06-04 43 views
5

考慮我有一個包含3條語句的try塊,並且它們都會導致異常。我希望所有的3個例外都能通過相關的catch塊來處理..有可能嗎?我可以執行多個與一個try塊對應的catch塊嗎?

是這樣的 - >

class multicatch 
{ 
    public static void main(String[] args) 
    { 
     int[] c={1}; 
     String s="this is a false integer"; 
     try 
     { 
      int x=5/args.length; 
      c[10]=12; 
      int y=Integer.parseInt(s); 
     } 
     catch(ArithmeticException ae) 
     { 
      System.out.println("Cannot divide a number by zero."); 
     } 
     catch(ArrayIndexOutOfBoundsException abe) 
     { 
      System.out.println("This array index is not accessible."); 
     } 
     catch(NumberFormatException nfe) 
     { 
      System.out.println("Cannot parse a non-integer string."); 
     } 
    } 
} 

是否有可能獲得以下輸出? - >>

Cannot divide a number by zero. 
This array index is not accessible. 
Cannot parse a non-integer string. 
+0

你認爲這樣的日誌消息會有什麼幫助嗎? –

回答

10

是否有可能獲得以下輸出?

不,因爲只有一個例外會被拋出。一旦拋出異常,執行將立即離開try塊,並假定有一個匹配的catch塊,它將繼續。它不會回到try區塊,所以你不能以第二個異常結束。

查看Java tutorial瞭解異常處理的一般教程,以及section 11.3 of the JLS瞭解更多詳情。

+0

哦,罰款.. thnks –

2

如果你想捕獲多個異常,你必須跨多個try/catch塊分割你的代碼。

更好的方法是驗證您的數據並記錄錯誤,而不觸發異常來執行此操作。

0

要添加到Jon的答案中,雖然您不會從單個try塊中捕獲多個異常,但您可以讓多個處理程序處理單個異常。

try 
{ 
    try 
    { 
     throw new Exception("This is an exception."); 
    } 
    catch(Exception foo) 
    { 
     System.Console.WriteLine(foo.Message); 
     throw; // rethrows foo for the next handler. 
    } 
} 
catch(Exception bar) 
{ 
    System.Console.WriteLine("And again: " + bar.Message); 
} 

這將產生輸出:

This is an exception. 
And again: This is an exception. 
0

這是一個REALY不好的做法,但你可以做下一個(解決使用finally塊您的問題):

private static void Main() 
     { 
      int[] c={1}; 
      String s="this is a false integer"; 
      try 
      { 
       int z = 0; 
       int x = 5/z; 
      } 
      catch (ArithmeticException exception) 
      { 
       Console.WriteLine(exception.GetType().ToString()); 
      } 
      finally 
      { 
       try 
       { 
        c[10] = 12; 
       } 
       catch(IndexOutOfRangeException exception) 
       { 
        Console.WriteLine(exception.GetType().ToString()); 
       } 
       finally 
       { 
        try 
        { 
         int y = int.Parse(s); 
        } 
        catch (FormatException exception) 
        { 
         Console.WriteLine(exception.GetType().ToString()); 
        } 
       } 

       Console.ReadKey(); 
      } 
     } 
0

顯示全部一次處理異常是不可能的。每個例外catch的目標是對每個Exception類型進行不同的處理,否則將它們全部打印在一起毫無意義。

0

沒有,

它不會執行所有三個catch語句。該塊將檢查錯誤,然後執行TRY塊。然後合適捕捉將被執行。就你而言,The ArithmeticException位於異常層次結構的頂部。所以它會執行,然後程序終止。

如果你給,趕上(例外五)ArithmeticException然後捕獲異常,將執行...更好地閱讀關於SystemException的層次結構MSDN