Catch multiple exceptions at once?

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

    This is a classic problem every C# developer faces eventually.

    Let me break your question into 2 questions. The first,

    Can I catch multiple exceptions at once?

    In short, no.

    Which leads to the next question,

    How do I avoid writing duplicate code given that I can't catch multiple exception types in the same catch() block?

    Given your specific sample, where the fall-back value is cheap to construct, I like to follow these steps:

    1. Initialize WebId to the fall-back value.
    2. Construct a new Guid in a temporary variable.
    3. Set WebId to the fully constructed temporary variable. Make this the final statement of the try{} block.

    So the code looks like:

    try
    {
        WebId = Guid.Empty;
        Guid newGuid = new Guid(queryString["web"]);
        // More initialization code goes here like 
        // newGuid.x = y;
        WebId = newGuid;
    }
    catch (FormatException) {}
    catch (OverflowException) {}
    

    If any exception is thrown, then WebId is never set to the half-constructed value, and remains Guid.Empty.

    If constructing the fall-back value is expensive, and resetting a value is much cheaper, then I would move the reset code into its own function:

    try
    {
        WebId = new Guid(queryString["web"]);
        // More initialization code goes here.
    }
    catch (FormatException) {
        Reset(WebId);
    }
    catch (OverflowException) {
        Reset(WebId);
    }
    

提交回复
热议问题