To Catch or Not To Catch

Earlier today, it came up in discussion, on when to catch exceptions. Really, you end up getting bitten if you just catch exceptions in your code. Basically what happens is that you are using exceptions as flow control, and not using if/end, etc. What usually ends up happening is an exception is getting eaten, but you didnt want it to, and you dont know how your program is reacting to use. ELMAH is great, you should set it up if you are using .NET programming. Also, and it is funny, but this always happens, Scott Hanselman blogged about almost the exact same topic today. And if you can avoid, dont catch a System.Exception – use a more specific exception. If you turn on Code Analysis or run FxCop, it will tell you about that as well.

Advertisements

One thought on “To Catch or Not To Catch”

  1. My recommendation is to only catch the exceptions you know you can handle and recover from. This avoids the nasty problem of being the man in the middle. Let’s say MethodA calls MethodB which calls MethodC. MethodC throws an exception, but MethodB catches everything to avoid “crashing.” Then MethodA has no chance to handle the exception, which it may very well be expecting and know how to recover from. Oops.

    The danger of this approach is that you will scare the user with unhandled exceptions. But is that any less scary than a crash? What’s more, if you handle all exceptions and you don’t know how to recover from it, your application is in a terribly hosed state anyways. How can you rely on invariants your code assumes when you can’t even tell what state you’re in?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s