Best Practice for Exception Handling in a Windows Forms Application?

前端 未结 16 2084
滥情空心
滥情空心 2020-11-29 14:20

I\'m currently in the process of writing my first Windows Forms application. I\'ve read a few C# books now so I\'ve got a relatively good understanding of what language feat

16条回答
  •  广开言路
    2020-11-29 15:23

    I deeply agree the rule of:

    • Never let errors pass unnoticed.

    The reason is that:

    • When you first write down the code, most likely you won't have the full knowledge of 3-party code, .NET FCL lirary, or your co-workers latest contributions. In reality you cannot refuse to write code until you know every exception possiblity well. So
    • I constanly find that I use try/catch(Exception ex) just because I want to protected myself from unknown things, and, as you noticed, I catch Exception, not the more specific such as OutOfMemoryException etc. And, I always make the exception being popped up to me(or the QA) by ForceAssert.AlwaysAssert(false, ex.ToString() );

    ForceAssert.AlwaysAssert is my personal way of Trace.Assert just regardless of whether the DEBUG/TRACE macro is defined.

    The development cycle maybe: I noticed the ugly Assert dialog or someone else complain to me about it, then I come back to the code and figure out the reason to raise the exception and decide how to process it.

    By this way I can write down MY code in a short time and protected me from unknown domain, but always being noticed if the abnormal things happened, by this way the system got safe and more safety.

    I know many of you wont agree with me because a developer should known every detail of his/her code, frankly, I'm also a purist in the old days. But nowdays I learned that the above policy is more pragmatic.

    For WinForms code, a golden rule I always obey is:

    • Always try/catch(Exception) your event handler code

    this will protected your UI being always usable.

    For performance hit, performance penalty only happens when the code reachs catch, executing try code without the actual exception raised has no significant effect.

    Exception should be happened with little chance, otherwise it's not exceptions.

提交回复
热议问题