Friday, November 1, 2013

Rule #1: Don't Swallow Exceptions!

Every now and again I come into an unexplainable bug, which takes me hours or even days to solve. Something goes wrong in the application, and there's no explanation to it. Nothing unusual in the logs, no exception stack trace exploding in the console. Noting.
After digging and digging in the code, I usually come into something like this:

private void foo() {
  try { 

    do something...
   }
   catch(SomeException e) { What we see here is a swallowed exception - an exception that is caught and not handled.
   // well, this shouldn't happen. bla bla
   }
}

What the ...? I wonder what went on in the dude who wrote this code's mind. Maybe you think it's impossible to get an exception in that try clause, but from my experience - expect the unexpected. Once you will get that exception for some reason you couldn't expect - the application's execution will be undefined, and unless you do something with that exception, there is no way to know why.

So for conclusion - do something with an exception you catch. Don't leave it hanging in there. Log it, throw it, any way you want it - just don't swallow it!

No comments:

Post a Comment