我可以执行多个Catch块吗?

这有点抽象,但是有没有办法抛出exception并让它进入多个catch块? 例如,如果它匹配特定exception后跟非特定exception。

catch(Arithmetic exception) { //do stuff } catch(Exception exception) { //do stuff } 

拥有不同类型的多个捕获块是完全可以接受的。 但是,行为是第一个候选块处理exception。

它不会进入BOTH catch块。 匹配exception类型的第一个catch块将处理该特定exception,而不处理其他exception,即使它在处理程序中重新抛出。 一旦exception进入catch块,将跳过任何后续的。

为了在BOTH块中捕获exception,您需要嵌套块,如下所示:

 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 } 

或者,您可以根据特定的exception类型过滤通用exception处理程序。

不可以。对于单个exception,不可能在两个catch块中执行代码。

我可能会将通用exception块中的代码重构为可以从其中调用的内容。

 try { // blah blah blah { catch(Arithmetic ae) { HandleArithmeticException( ae ); HandleGenericException( ae ); } catch(Exception e) { HandleGenericException( e ); } 

像其他人一样,exception将被最具体的catch块捕获。

这带来了我的挫败感,但有exception处理。 我希望你能做点什么

 catch (ArgumentNullExcpetion, ArugmentOutOfRangeException ex) { } 

而不是必须这样做

 catch (ArgumentNullExcpetion e) { } catch (ArugmentOutOfRangeException outOfRange) { } 

我理解反对这个的理由,你可能会为不同的例外做不同的事情,但有时我想要结合它们。

如果您使用的是VB.NET,则可以将Arithmeticexception中的error handling程序抽象为始终返回false的函数或方法调用。

然后你可以写下这样的东西:

 Catch ex as Arithmetic When HandleArithmetic() Catch ex as Exception End Try 

不是我会提倡这样的用法,虽然我之前已经看过它建议用于记录目的。 我不相信有一个C#等价物。

您不能有多个exception块处理相同的exception。 但你可以做的是捕获一般exception,然后尝试转换为更具体的,如下所示:

 catch (Exception exception) { var aex = exception as ArithmeticException if (aex != null) { // do stuff specific to this exception type } // then do general stuff } 

这称为exception过滤,在C#中不受支持(我告诉它可以在VB.NET中使用)。

一个解决方法是捕获一般exception,然后检查catch块中的exception类型,并在继续执行块的其余部分之前对其进行任何特定处理。