Catch multiple exceptions at once?

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

    Maybe try to keep your code simple such as putting the common code in a method, as you would do in any other part of the code that is not inside a catch clause?

    E.g.:

    try
    {
        // ...
    }
    catch (FormatException)
    {
        DoSomething();
    }
    catch (OverflowException)
    {
        DoSomething();
    }
    
    // ...
    
    private void DoSomething()
    {
        // ...
    }
    

    Just how I would do it, trying to find the simple is beautiful pattern

提交回复
热议问题