jon*_*jon 23 c# exception-handling try-catch
这有点抽象,但是有没有办法抛出异常并让它进入多个catch块?例如,如果它匹配特定异常后跟非特定异常.
catch(Arithmetic exception)
{
//do stuff
}
catch(Exception exception)
{
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
Ree*_*sey 39
拥有不同类型的多个捕获块是完全可以接受的.但是,行为是第一个候选块处理异常.
它不会进入BOTH catch块.匹配异常类型的第一个catch块将处理该特定异常,而不处理其他异常,即使它在处理程序中重新抛出.一旦异常进入catch块,将跳过任何后续的.
为了在BOTH块中捕获异常,您需要嵌套块,如下所示:
try
{
try
{
// Do something that throws ArithmeticException
}
catch(ArithmeticException arithException)
{
// This handles the thrown exception....
throw; // Rethrow so the outer handler sees it too
}
}
catch (Exception e)
{
// This gets hit as well, now, since the "inner" block rethrew the exception
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以根据特定的异常类型过滤通用异常处理程序.
tva*_*son 21
不可以.对于单个异常,不可能在两个catch块中执行代码.
我可能会将通用异常块中的代码重构为可以从其中调用的内容.
try
{
// blah blah blah
{
catch(Arithmetic ae)
{
HandleArithmeticException( ae );
HandleGenericException( ae );
}
catch(Exception e)
{
HandleGenericException( e );
}
Run Code Online (Sandbox Code Playgroud)
就像其他人所说的那样,异常将被最具体的 catch 块捕获。
尽管异常处理,这还是让我感到沮丧。我希望你能做类似的事情
catch (ArgumentNullExcpetion, ArugmentOutOfRangeException ex)
{
}
Run Code Online (Sandbox Code Playgroud)
而不是必须做
catch (ArgumentNullExcpetion e)
{
}
catch (ArugmentOutOfRangeException outOfRange)
{
}
Run Code Online (Sandbox Code Playgroud)
我理解反对这一点的理由,即您可能会针对不同的异常执行不同的操作,但有时我想将它们结合起来。