Catch multiple exceptions at once?

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

    For the sake of completeness, since .NET 4.0 the code can rewritten as:

    Guid.TryParse(queryString["web"], out WebId);
    

    TryParse never throws exceptions and returns false if format is wrong, setting WebId to Guid.Empty.


    Since C# 7 you can avoid introducing a variable on a separate line:

    Guid.TryParse(queryString["web"], out Guid webId);
    

    You can also create methods for parsing returning tuples, which aren't available in .NET Framework yet as of version 4.6:

    (bool success, Guid result) TryParseGuid(string input) =>
        (Guid.TryParse(input, out Guid result), result);
    

    And use them like this:

    WebId = TryParseGuid(queryString["web"]).result;
    // or
    var tuple = TryParseGuid(queryString["web"]);
    WebId = tuple.success ? tuple.result : DefaultWebId;
    

    Next useless update to this useless answer comes when deconstruction of out-parameters is implemented in C# 12. :)

提交回复
热议问题