Catching base Exception class in .NET

前端 未结 16 1948
心在旅途
心在旅途 2020-12-05 19:06

I keep hearing that

catch (Exception ex)

Is bad practise, however, I often use it in event handlers where an operation may for example go

16条回答
  •  死守一世寂寞
    2020-12-05 19:31

    When I see

    catch (Exception ex)
    

    my hand starts to groping for a hammer. There are almost no excuses to catch base Exception. Only valid cases that come to my mind are:
    1) 3rd party component throws Exception (be damned it's author)
    2) Very top level exceptions handling (as a last resort) (for example handle "unhandled" exceptions in WinForms app)

    If you find a case where many different types of exceptions can happen it's a good sign of bad design.

    I would disagree with Armin Ronacher. How would you behave if StackOverflow exception raised? Trying to perform additional actions can lead to even worse consequences. Catch exception only if you can handle it in meaningful and safe way. Catching System.Exception to cover range of possible exceptions is terribly wrong. Even when you are re-throwing it.

提交回复
热议问题