C# equivalent to VB.NET's Catch…When

后端 未结 3 1276
栀梦
栀梦 2021-01-04 04:40

In VB.NET I often Catch…When:

Try
    …
Catch e As ArgumentNullException When e.ParamName.ToUpper() = \"SAMPLES\"
    …
End Try
<
3条回答
  •  长发绾君心
    2021-01-04 05:11

    That won't recreate the same semantics as the VB Catch When expression. There is one key difference. The VB When expression is executed before the stack unwind occurs. If you were to examine the stack at the point of a when Filter, you would actually see the frame where the exception was thrown.

    Having an if in the catch block is different because the catch block executes after the stack is unwound. This is especially important when it comes to error reporting. In the VB scenario you have the capability of crashing with a stack trace including the failure. It's not possible to get that behavior in C#.

    EDIT:

    Wrote a detailed blog post on the subject.

提交回复
热议问题