2013-06-04 33 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