Catch multiple exceptions at once?

前端 未结 27 2369
夕颜
夕颜 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

    The accepted answer seems acceptable, except that CodeAnalysis/FxCop will complain about the fact that it's catching a general exception type.

    Also, it seems the "is" operator might degrade performance slightly.

    CA1800: Do not cast unnecessarily says to "consider testing the result of the 'as' operator instead", but if you do that, you'll be writing more code than if you catch each exception separately.

    Anyhow, here's what I would do:

    bool exThrown = false;
    
    try
    {
        // Something
    }
    catch (FormatException) {
        exThrown = true;
    }
    catch (OverflowException) {
        exThrown = true;
    }
    
    if (exThrown)
    {
        // Something else
    }
    

提交回复
热议问题