Don't touch that exception!

time to read 2 min | 269 words

It is evil to swallow exceptions. I am working with a library that is choked full with stuff like:

try {
 //do stuff
 }
catch (Exception e){
 Trace.WriteLine(e.Message, "Name of the method");
}

This is a UI component, and it is driving me mad. Stuff stops working all of a sudden, and I need to run the app under the debugger with "catch all exception" to find out what is going on. The exception message itself (when I manage to find it) is often not very helpful, and I don't get the stack.
My rules for exceptions are:
- Always throw exceptions if conditions are not valid.
- Throw exception as soon as possible and give as much information as you can.
- Business logic and UI code shouldn't deal with exceptions, but bubble them through.
- It is evil and nasty and wrong and vile and naughty and dishost to swallow an exception, even if you log it.

For instance, there is quite a bit of work in Rhino Mocks to provide good exceptions messages, even at the cost of increased comlexity. It works.

The only place where you need to handle an exception is in the high level controller code, that has all the information about the current operation. (Looks like we can't make the file transfer work, we need to page the admin about it...). Exception handling is a policy decision that is dependant on the current context of the operation ("We can't find the resource for ancient greeek, so we will use the default English one") and cannot be reliabely handled by lower layers.

Update: Fixed broken sentence, thanks Bob.