If you try exceptional code, make sure you catch the exceptions

Recently, an application failed on me. And I didn’t receive any notification. I only knew it failed because the next hour, I received a notification that it couldn’t start. Let me tell you more about the application first.

The application was supposed to run every hour. At the start, it would update a datetime column in the database. At the end, it would update another datetime column in the database. On start, before continuing with the bulk of its operations, the application checked that the start date was earlier than the end date (from the previous operations). This way, it won’t accidentally run once more while presumably another copy of itself was running.

Anyway, if it did happen to hit that start-date-later-than-end-date condition, then it failed. And a notification would be sent to me. The details were logged in a log file. Due to some complexities of its implementation, I had to check the log file of the earlier run to get the details.

And I found nothing. I mean the log file obviously wasn’t complete. But the error message wasn’t there. I was perplexed. I remembered there was a giant try-catch clause in the program, so I should at least see something. Can you see the flaw?

try
{
    // do stuff here
}
catch (SqlException se)
{
    log.WriteLog(se.ToString());
}
catch (OleDbException oe)
{
    log.WriteLog(oe.ToString());
}

What if the exception wasn’t database-related? And that’s exactly what happened. There was an input file, and it wasn’t properly formatted, thus creating all sorts of parsing errors. It was an IO problem. Since the action taken was the same in exceptional cases, I rewrote the above to this:

try
{
    // do stuff here
}
catch (Exception e)
{
    log.WriteLog(e.ToString());
}

If you’re going to catch specific exceptions, make sure you catch all of them.