Back to basic with the Try Catch statement
Over the last 2 months I have been quite busy at my new job, where I`m trying to raise the quality of code (just to mention one thing) - not only with our own code, but also with 3rdparty web applications that we have bought.
I have discovered a really annoying thing lately and that is people are misusing the Try Catch statement. At first I thought that this was something only relatively new developers did but it seems like some people continue to use it wrong.
Example 1
1 2 3 4 5 6 | try{ // lines of code } catch(){ // do nothing } |
When you talk with them about this form of error handling, they usually come up with an argument like “We don`t want the application to fail” and it is valid point of view, but there are issues when following Example 1.
Not only is it what you call smelly code, it can also give a serious headache when trying to look for a bug in the system, because the above example will just let the program continue and hope that it will “complete” whatever operation it is doing.
Rule 1
First of all, it says something about that you are trying to handle some sort exception that shouldn`t be raised in the first place. Determine what causes the exception and either rewrite the code inside the Try Catch statement (even removing it completely) or fix the Catch() so that it handles the exception correctly (see rule 2 and 3).
Remember: Try Catch statements are among the biggest resource eating operations you can perform.
Rule 2
If you really need to Catch an exception make sure that you log it somehow.
1 2 3 4 | catch(exception ex) { LogException('something went wrong'); } |
Rule 3
Rule 3 is an extension to rule 2
When you want to catch an exception, you should make sure that you don’t catch it with a non-specific exception like Exception. Exceptions should be handled as unexpected events that you intend to (or can) do something specific about. It doesn’t make sense to handle many different things, at the same time, with Exception, so is you want to catch a FormatException or SqlException, then you should use one of those instead, it also gives you a more precise idea on what to expect when reading the code.
Finally, consider whether your program really needs to handle exceptions, period. As Bjarne Stroustrup points out, sometimes the best response to a serious run-time error is to release all acquired resources and abort. Let the user rerun the program with proper input
- Code Complete (second edition)
You can read more about good code practise in Code Complete by Steven McConnell.