Finding Unhandled Exceptions - .NET
I have a fairly large .NET solution that has poor exception handling. The original authors meant well, catching specific types of exceptions rather than the base exception class, however, this has resulted in more than I can count places where exceptions of a type are thrown but not caught anywhere and makes the software unreliab开发者_运维知识库le. How can I perform a code analysis to identify where in the solution an exception type can be thrown but is not being caught?
You can add a global exception handler that logs the Exception including stack trace, and puts up a nice error dialog for the user. You can use the stack trace to identify the places in the code that generates errors and put up better handling of those scenarios. Log as much as possible.
How you do that depends on the platform (WebForms, MVC, WinForms, WPF, ... ?)
Also, an in-depth code review of the entire code base with emphasis on error handling might catch many errors before they manifest themselves as errors to the user.
This is how I handle them. In my Program.cs
in the Main
method, I set up event handling. After, you put in these events the code your want.
Application.ThreadException += Form1_UIThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
EDIT: This is for non-web based apps.
Any exception that is not caught is unhandled. The good news is you can subscribe to that AppDomain.CurrentDomain.UnhandledException event.
This handles any exception that is thrown that is not caught.
How can I perform a code analysis to identify where in the solution an exception type can be thrown but is not being caught?
There are programs like StyleCop that will highlight possible unhandled exceptions.
精彩评论