Ivan Mitev In The Software Trenches

Technology weblog on .NET development and other things that make the world go round

March 10, 2005

What exceptions to expect?

I wrote a function that calls Convert.ChangeType(object val,TypeCode code) to check if a given value can be converted to the specified TypeCode. And I would like to adhere to the rule "Catch only the exceptions that you expect". But what can one expect? Initially I expected 2 types of exceptions: InvalidCastException and FormatException. Then in a test case I found out that
OverflowException is also occurs in some cases. So, I added another catch block...

You see, I am not even 50% sure that I am handling all the possible exception types. I guess, I could spend a few days reading documentation and investigating with Reflector. And even dissambly can not help in some cases where unmanaged code is used (this applies to the example). So, is it worth the effort? Or better just do catch(Exception ex)? If I catch a generic exception, it might turn out to be a memory exception. And sure, it is not the best idea to say that the format of val was invalid, when you are out of memory. But since I can't recover from memory exceptions, what's the point of handling those?

2 Comments:

If you use catch(Exception ex) that is the most terrible thing you can do. You can spend endless nights in a production system trying to figure out what the %##$ is happening. In my opinion you should only catch those exceptions you are aware of. And only if can recover from them. All other exceptions are really exception case for you and you should let them bubble up to the unhandled exception handler.

By Anonymous Martin Kulov, at 11 March, 2005 02:11  

Ideally that's right. But we are living in an inperfect world :) .

In the single statement Convert.ChangeType() all the possible exceptions (excluding a system failure, which is unrecoverable anyway) have the semantics of "the value can not be converted to the wanted type". If the code doesn't care about the detailed reason, there is nothing that wrong about this way of handling exceptions.

Even suppose that OutOfMemoryException is caught (which, you know, is pretty unlikely to happen in the exact statament). If the OutOfMemoryException is swallowed by the catch(Exception) block there is a 99.99% probability that some of the next statements would again lead to OutOfMemoryException, so we have not done anything that wrong.

By Blogger Ivan Mitev, at 11 March, 2005 09:55  

Post a Comment

<< Home