And there was much rejoicing, for the Exception was raised

time to read 5 min | 812 words

A lot of programmers seems to be afraid of exceptions. The moment they get one they throw their hands up in dispair and exclaim "This piece of shit doesn't work." And then they come to me to help. They usually start with "It threw an error", "It doesn't work", etc.

At first I try to hone my clairvoyant skills, and give them an answer anyway, but after being accused for using KGB interrogation technique* I decided to stop that. Nowadays, I refuse to help them unless they tell me what the exception is. And in 97% of the cases, it is a simple thing like a bad connection string, trying to do things wrong, etc.

I like exceptions, they give you information about the error. They are descriptive, they stop you from carrying on with an error. I just worked on a codebase that looked mostly like this:

public bool DoWork()
{
  try
  { 
      // do work
      return true;
   } 
   catch (Exception e)
   {
     //maybe log exception
     return false
   }
}

A fair warning, if you are writing code like this, it has better be in a method called IsPossibleToXXXX(), and it should be called once. Failing to do will result in me coming after your with a big stick. I

The calling code was sometimes check the return code, and sometimes didn't, and when it failed, it took forever to hunt it down. It is nice that you are showing off you C master level skills, but it's not C anymore. No, logging the exception doesn't help. I don't want to look at the log when I am running the app. And don't even get me started on logging exceptions like this:

catch(Exception e)
{
   logger.Error(e.Message);

}

Talk about useless logging. The most common exception in NHibernate is "unable to perform find", with all the nice juicy details hidden about two layers down. Logging just the message is wrong. Log everything, you wouldn't believe the amount of information just the call stack can give you.

I had a devil of a time removing a lot of that exception handling, and you wouldn't believe my excitement when I got the first exception (Null Reference Exception) throught all the layers in that application. Now I could work properly.

A proper application should have only a couple try/catch blocks, and those should be at the very top of the call chain.I just finish writing an app that needed to be exceptions harden, this meant that nothing should take it down, DB down, collaborators down, etc. I had to add a lot of try / catch blocks in a single class. I didn't litter my code with them like a prankster on drugs.

Oh, and no matter what you think, exceptions are so much better than ERROR 0x030984542 OCCURED!

* I got some key parses in Russian tphat roll of the tongue just nicely. The Russian speaking guys here are shocked each time I am saying it. But they refuse to translate it. It is something about a cow and your mother, I think. Great for relieving pressure. There is blat in it somewhere too.