When I was a coding newbie I thought applications should never crash. I wrote code that caught and ignored errors because I didn’t know how else to handle them. I didn’t want the user to see an error page, and figured a running application was always better than an error page. Oh, how wrong I was. On one application alone (not written by me) I wasted 50+ hours over the course of a few months because of exceptions that were caught and not properly handled. Don’t let this happen to you.
I’ve found this mindset to be so common among new developers that I’ve distilled the basics down to two fundamental rules a new developer should follow to the letter. I’m exhausted with cracking open code and seeing a Try/Catch block with no action after the catch. Whether you’re using a language with actual exceptions is beside the point – what matters is that you read through these few simple paragraphs and never, ever obfuscate your application errors.
Picture this (in C#):
‘ Application code here
‘ Do nothing
What happens when an exception is thrown from the application code? Nothing…and that’s a problem.
Let’s say the application is attempting to insert a value into the database. Instead of a crash and some type of error message (even the default message would be helpful), the program continues to execute. At some point in the future, perhaps seconds, minutes, or weeks, another piece of code comes along looking for that database value and doesn’t find it. The result is a crash. Well, hopefully a crash. An even more likely case is that it will continue to execute and write 1s and 0s over the only remaining copy of your grandmother’s priceless rhubarb pie recipe. Or worse, the only remaining copy of the financial statements for your grandmother’s rhubarb pie factory. Yes sir, dirty data is eeee-vil.
With that in mind, let’s take a look at these two simple rules:
Rule #1: If you can’t add helpful information to an error message, don’t catch the exception.
If you are simply going to catch and re-throw an exception, you are better off removing your Try/Catch block and letting the runtime throw the exception for you. In other words, if you don’t know why you’re adding a try/catch block, don’t add it.
Rule #2: If you catch an exception, log it.
I’ve seen this rule broken in at least 10 applications in the past 6 months. Use log4j, log4net, Microsoft’s Logging Application Block, a text file, morse code, or carrier pigeon…just log the damn thing. Never catch an exception and do nothing unless you are writing a tool used to log exceptions.
Logging exceptions is not just a good idea, it allows you to know about errors before your customer does and is an invaluable tool for maintaining a healthy application.
If you have other exception management suggestions feel free to post them to the comments.
[tags]asp.net, .net, exceptions, error handling[/tags]