Catch multiple exceptions at once?

前端 未结 27 1892
夕颜
夕颜 2020-11-22 11:31

It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

Now, this sometimes leads to unnecce

27条回答
  •  孤街浪徒
    2020-11-22 12:17

    Not in C# unfortunately, as you'd need an exception filter to do it and C# doesn't expose that feature of MSIL. VB.NET does have this capability though, e.g.

    Catch ex As Exception When TypeOf ex Is FormatException OrElse TypeOf ex Is OverflowException
    

    What you could do is use an anonymous function to encapsulate your on-error code, and then call it in those specific catch blocks:

    Action onError = () => WebId = Guid.Empty;
    try
    {
        // something
    }
    catch (FormatException)
    {
        onError();
    }
    catch (OverflowException)
    {
        onError();
    }
    

提交回复
热议问题