C# 我可以执行与一个 try 块相对应的多个 catch 块吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16927406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I execute multiple catch blocks that correspond to one try block?
提问by Srinivas Cheruku
Consider I have a try block that contains 3 statements, and all of them cause Exceptions. I want all the 3 exceptions to be handled by their relevant catch blocks.. is it possible ?
考虑我有一个包含 3 个语句的 try 块,并且所有这些语句都会导致异常。我希望所有 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.
采纳答案by Jon Skeet
Is it possible to obtain the following output?
是否可以获得以下输出?
No, because only one of the exceptions will be thrown. Execution leaves the tryblock as soon as the exception is thrown, and assuming there's a matching catchblock, it continues there. It doesn't go back into the tryblock, so you can't end up with a second exception.
不,因为只会抛出其中一个异常。try一旦抛出异常,执行就会离开块,假设有一个匹配的catch块,它会在那里继续。它不会返回到try块中,因此您不会以第二个异常结束。
See the Java tutorialfor a general lesson in exception handling, and section 11.3 of the JLSfor more details.
有关异常处理的一般课程,请参阅Java 教程,有关更多详细信息,请参阅 JLS 的 11.3 节。
回答by Peter Lawrey
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.
更好的方法是验证您的数据并记录错误,而无需触发 Exceptions 来执行此操作。
回答by James T
To add to Jon's answer, while you won't catch multiple exceptions from a single tryblock, 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.
回答by Dzmitry Martavoi
this is a REALY BAD PRACTICE, but you can do next (solve your problem using finallyblock):
这是一个非常糟糕的做法,但你可以做下一步(使用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();
}
}
回答by Yair Nevet
Showing all of the exceptions handling at once is impossible. The goal of each exception catchis to have a different handling for each Exceptiontype and otherwise it's pointless to print them all together.
一次显示所有异常处理是不可能的。每个异常的目标catch是对每种Exception类型进行不同的处理,否则将它们一起打印是毫无意义的。
回答by Balaji
No ,
不 ,
It will not execute all three catch statements. The TRYblock checks for error and then the execution comes out of the TRY block. Then Suitablecatch will be executed. In your case, The ArithmeticExceptionis in the Top of the Exception Hierarchy. So it will Execute and then the program terminates.
它不会执行所有三个 catch 语句。所述TRY为误差块的检查,然后将执行来自try块的进行。然后将执行合适的捕获。在您的情况下,ArithmeticException位于异常层次结构的顶部。所以它将执行,然后程序终止。
If you give, Catch(Exception e)before ArithmeticExceptionthen Exception catch will be executed... Better read about the SystemException Hierarchies at MSDN
如果你给,Catch(Exception e)before ArithmeticException然后异常捕获将被执行......更好地阅读MSDN 上的 SystemException Hierarchies

