Exceptions and Return Codes
October 18th, 2006[ Software Development ]
The religious argument of exceptions versus return codes comes up more often than I honestly thought it would. Maybe I’ve been isolated in my exception based cave all this time?
I’ve travelled a path that started out return code based by virtue of being in the early Microsoft web days. I then came out of the return code forest onto the exception path. I personally prefer the exception path, unfortunately it seems that people in the return code forest like to climb the trees and chuck rotten apples at us clean living exception path people trying to mind our own business.
My personal take? This is one of the few topics I don’t see eye to eye with Joel on. Apparently I’m not alone on this.
I also agree with Raymond that exception based code is more difficult to write well. So is raising three children instead of one but that doesn’t mean it’s to be avoided.
Is it simpler to write return based code? Yes. Does it sometimes require more design, more thought to write good exception based code? Yes. Does that convince me to revert to return based code? No. Is this writing style of asking myself questions lame? Clearly.
The whole ‘using exceptions for business processing’ argument always comes up as part of this. My rule, which is relatively standard, is the 70/30 rule. Exceptions should be returned from a method no more than 30% of the calls to it. More than 30% means it is no longer considered an exceptional situation and the code should be tagged for refactoring.
It’s actually kinda simple, only throw exceptions in exceptional situations, it’s built right into the name. Sometimes you won’t know what that is until you get an application into production which is where the 70/30 rule comes in. Do your best, profile, refactor as needed.
If you follow the 70/30 rule then it means that the whole performance bogey man doesn’t exist. The point of exception based code is that everyday typical processing doesn’t encounter the overhead of throwing exceptions and therefore doesn’t suffer from any performance hit. If you’re throwing exceptions from a method for 50% of the calls to it those cases can’t really be considered exceptional cases can they? Ie, you’ve written poor exception based code. That’s fine, fix it, don’t give up on the entire concept.