开发者

How would I know if I haven't handled some unchecked exceptions that my .NET code could throw?

开发者 https://www.devze.com 2022-12-19 00:46 出处:网络
In .NET, method s开发者_开发技巧ignatures don\'t tell me if I have missed handling some exceptions that could be thrown by my code.

In .NET, method s开发者_开发技巧ignatures don't tell me if I have missed handling some exceptions that could be thrown by my code. Is there some tool that can warn me, if say I am using a HashTable remove but haven't handled the ArgumentNullException? I don't want to be surprised at run time.

And does this mean that you need to know your code very well, otherwise unchecked exceptions can be harder to work with?


Actually, handling unexpected exceptions by terminating the program is the best way to deal with this situation, since, in general, the program state is undefined when something unexpected happens. If you log all exceptions, and have a decent set of acceptance tests, you can eliminate problems which come from unexpected exceptions due to program flow.

Defensive programming by checking method inputs, unit tests of classes and understanding your framework will make most exceptions expected.


For windows applications:

AppDomain currentDomain = default(AppDomain);
currentDomain = AppDomain.CurrentDomain;
// Handler for unhandled exceptions.
currentDomain.UnhandledException += UnhandledExceptionHandler;
// Handler for exceptions in threads behind forms.
Application.ThreadException += ThreadExceptionHandler;

public static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
}

public static void ThreadExceptionHandler(object sender, Threading.ThreadExceptionEventArgs e)
{
}


There is no language support for what you are attempting to accomplish. We wrote a customs addin to VS to make sure that all the entry points for our API had try catches for logging. However I never saw the value in languages that forced you to cover all possible declared exception cases since you still have to write some code to do something meaningful with the error. Most people just look at what the complier is complaining about write a handler and hide what could be a useful error in some useless code. In some cases its better to fail and know there is a problem.


You should add topmost level exception handler for your application and write unit, functional and integration test for your app, which will test all possible use cases. This will help you to eliminate almost all unchecked exceptions.

Also try not to catch exceptions, but eliminate the reason. (i.e. Not catch ArgumentNullException but do not passing null

0

精彩评论

暂无评论...
验证码 换一张
取 消