Catch multiple exceptions at once?

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

    So you´re repeating lots of code within every exception-switch? Sounds like extracting a method would be god idea, doesn´t it?

    So your code comes down to this:

    MyClass instance;
    try { instance = ... }
    catch(Exception1 e) { Reset(instance); }
    catch(Exception2 e) { Reset(instance); }
    catch(Exception) { throw; }
    
    void Reset(MyClass instance) { /* reset the state of the instance */ }
    

    I wonder why no-one noticed that code-duplication.

    From C#6 you furthermore have the exception-filters as already mentioned by others. So you can modify the code above to this:

    try { ... }
    catch(Exception e) when(e is Exception1 || e is Exception2)
    { 
        Reset(instance); 
    }
    

提交回复
热议问题