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

2019-02-12 03:09发布

In VB.NET I often Catch…When:

Try
    …
Catch e As ArgumentNullException When e.ParamName.ToUpper() = "SAMPLES"
    …
End Try

Is there a C# equivalent to Catch…When?

I don't want to resort to using an if statement inside a catch if possible.

3条回答
趁早两清
2楼-- · 2019-02-12 03:20

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-02-12 03:28

This functionality was announced for C# 6. It is now possible to write

try { … }
catch (MyException e) when (myfilter(e))
{
    …
}

You can download the preview of Visual Studio 2015 now to check this out, or wait for the official release.

查看更多
放我归山
4楼-- · 2019-02-12 03:35

There's no equivalent to Catch…When in C#. You will really have to resort to an if statement inside your catch, then rethrow if your condition isn't fulfilled:

try
{
    …
}
catch (ArgumentNullException e)
{
    if ("SAMPLES" == e.ParamName.ToUpper())
    {
        … // handle exception
    }
    else
    {
        throw;  // condition not fulfilled, let someone else handle the exception
    } 
}
查看更多
登录 后发表回答