Catch multiple exceptions at once?

前端 未结 27 2302
夕颜
夕颜 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:11

    With C# 7 the answer from Michael Stum can be improved while keeping the readability of a switch statement:

    catch (Exception ex)
    {
        switch (ex)
        {
            case FormatException _:
            case OverflowException _:
                WebId = Guid.Empty;
                break;
            default:
                throw;
        }
    }
    

    And with C# 8 as switch expression:

    catch (Exception ex)
    {
        WebId = ex switch
        {
            _ when ex is FormatException || ex is OverflowException => Guid.Empty,
            _ => throw ex
        };
    }
    

提交回复
热议问题