Best Practice for Exception Handling in a Windows Forms Application?

前端 未结 16 2001
滥情空心
滥情空心 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:20

    A few more bits ...

    You absolutely should have a centralized exception handling policy in place. This can be as simple as wrapping Main() in a try/catch, failing fast with a graceful error message to the user. This is the "last resort" exception handler.

    Preemptive checks are always correct if feasible, but not always perfect. For example, between the code where you check for a file's existence and the next line where you open it, the file could have been deleted or some other issue may impede your access. You still need try/catch/finally in that world. Use both the preemptive check and the try/catch/finally as appropriate.

    Never "swallow" an exception, except in the most well-documented cases when you are absolutely, positively sure that the exception being thrown is livable. This will almost never be the case. (And if it is, make sure you're swallowing only the specific exception class -- don't ever swallow System.Exception.)

    When building libraries (used by your app), do not swallow exceptions, and do not be afraid to let the exceptions bubble up. Do not re-throw unless you have something useful to add. Do not ever (in C#) do this:

    throw ex;
    

    As you will erase the call stack. If you must re-throw (which is occasionally necessary, such as when using the Exception Handling Block of Enterprise Library), use the following:

    throw;
    

    At the end of the day, the very vast majority of exceptions thrown by a running application should be exposed somewhere. They should not be exposed to end users (as they often contain proprietary or otherwise valuable data), but rather usually logged, with administrators notified of the exception. The user can be presented with a generic dialog box, maybe with a reference number, to keep things simple.

    Exception handling in .NET is more art than science. Everyone will have their favorites to share here. These are just a few of the tips I've picked up using .NET since day 1, techniques which have saved my bacon on more than one occasion. Your mileage may vary.

    0 讨论(0)
  • 2020-11-29 15:20

    The one thing I learned very quickly was to enclose absolutely every chunk of code that interacts with anything outside the flow of my program (i.e. File System, Database Calls, User Input) with try-catch blocks. Try-catch can incur a performance hit, but usually in these places in your code it won't be noticeable and it will pay for itself with safety.

    I have used empty catch-blocks in places where the user might do something that isn't really "incorrect", but it can throw an exception...an example that comes to mind is in a GridView if the user DoubleCLicks the gray placeholder cell on the top-left it will fire the CellDoubleClick event, but the cell doesn't belong to a row. In that case, you dont really need to post a message but if you don't catch it it will throw an unhandled exception error to the user.

    0 讨论(0)
  • 2020-11-29 15:23

    When should I re-throw an exception?

    Everywhere, but end user methods... like button click handlers

    Should I try to have a central error-handling mechanism of some kind?

    I write a log file... pretty easy for a WinForm app

    Do handling exceptions which might be thrown have a performance hit compared with pre-emptively testing things like whether a file on disk exists?

    I'm not sure about this, but I believe it is a good practice to thow exceptions... I mean you can ask whether a file exists and if it doesn't throw a FileNotFoundException

    Should all executable code be enclosed in try-catch-finally blocks?

    yeap

    Are there any times when an empty catch block might be acceptable?

    Yes, let's say you want to show a date, but you have no clue how that date was stores (dd/mm/yyyy, mm/dd/yyyy, etc) you try tp parse it but if it fails just keep going... if it is irrelevant to you... I would say yes, there is

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题