Best Practice for Exception Handling in a Windows Forms Application?

前端 未结 16 2048
滥情空心
滥情空心 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 14:58

    I'm just on my way out but will give you a brief run down on where to use exception handling. I will attempt to address your other points when I return :)

    1. Explicitly check for all known error conditions*
    2. Add a try/catch around the code if your are unsure if you were able to handle all cases
    3. Add a try/catch around the code if the .NET interface you are calling throws an exception
    4. Add a try/catch around the code if it crosses a complexity threshold for you
    5. Add a try/catch around the code if for a sanity check: You are asserting THIS SHOULD NEVER HAPPEN
    6. As a general rule, I do not use exceptions as a replacement for return codes. This is fine for .NET, but not me. I do have exceptions (hehe) to this rule though, it depends on the architecture of the application your are working on as well.

    *Within reason. There is no need to check to see if say a cosmic ray hit your data causing a couple bits to get flipped. Understanding what is "reasonable" is an acquired skill for an engineer. It's hard to quantify, yet easy to intuit. That is, I can easily explain why I use a try/catch in any particular instance, yet I am hard pressed to imbue another with this same knowledge.

    I for one tend to steer away from heavily exception based architectures. try/catch doesn't have a performance hit as such, the hit comes in when the exception is thrown and the code might have to walk up several levels of the call stack before something handles it.

提交回复
热议问题