简体   繁体   English

我可以执行与一个try块对应的多个catch块吗?

[英]Can I execute multiple catch blocks that correspond to one try block?

Consider I have a try block that contains 3 statements, and all of them cause Exceptions. 考虑我有一个包含3个语句的try块,所有这些语句都会导致异常。 I want all the 3 exceptions to be handled by their relevant catch blocks.. is it possible ? 我希望所有3个例外都由它们相关的catch块处理..是否可能?

something like this--> 像这样的东西 - >

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.");
        }
    }
}

Is it possible to obtain the following output? 是否有可能获得以下输出? -->> - >>

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

Is it possible to obtain the following output? 是否有可能获得以下输出?

No, because only one of the exceptions will be thrown. 不,因为只会抛出一个异常。 Execution leaves the try block as soon as the exception is thrown, and assuming there's a matching catch block, it continues there. 一旦抛出异常,执行就会离开try块,并且假设有一个匹配的catch块,它会继续存在。 It doesn't go back into the try block, so you can't end up with a second exception. 它不会返回到try块,因此您无法获得第二个异常。

See the Java tutorial for a general lesson in exception handling, and section 11.3 of the JLS for more details. 有关异常处理的一般课程,请参阅Java教程 ,有关详细信息,请参阅JLS的第11.3节

If you want to catch multiple exceptions, you have to split your code across multiple try/catch blocks. 如果要捕获多个异常,则必须将代码拆分为多个try / catch块。

A better approach is to validate your data and log errors without triggering Exceptions to do this. 更好的方法是验证数据和记录错误,而不会触发例外来执行此操作。

To add to Jon's answer, while you won't catch multiple exceptions from a single try block, you can have multiple handlers handle a single exception. 要添加到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 produces the output: 这会产生输出:

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

this is a REALY BAD PRACTICE, but you can do next (solve your problem using finally block): 这是一个REALY BAD PRACTICE,但你可以做下一个(使用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();
            }
        } 

Showing all of the exceptions handling at once is impossible. 一次显示所有异常处理是不可能的。 The goal of each exception catch is to have a different handling for each Exception type and otherwise it's pointless to print them all together. 每个异常catch的目标是对每个Exception类型进行不同的处理,否则将它们全部打印在一起是没有意义的。

No , 不,

It will not execute all three catch statements. 它不会执行所有三个catch语句。 The TRY block checks for error and then the execution comes out of the TRY block. TRY块检查错误,然后执行从TRY块中出来。 Then Suitable catch will be executed. 然后执行合适的捕获。 In your case, The ArithmeticException is in the Top of the Exception Hierarchy. 在您的情况下, ArithmeticException位于异常层次结构的顶部。 So it will Execute and then the program terminates. 因此它将执行,然后程序终止。

If you give, Catch(Exception e) before ArithmeticException then Exception catch will be executed... Better read about the SystemException Hierarchies at MSDN 如果在ArithmeticException之前给出Catch(Exception e) ,那么将执行Exception catch ...更好地阅读MSDN上的SystemException层次结构

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM