Don't Use Exceptions for Flow Control

I just read a blog entry titled A word from the “Wise”: Don’t Use Exceptions on Alex Papadimoulis’ weblog. He describes in great length how a so-called MVP had told him that using exceptions was a bad idea and continues to prove in ten points why he doesn’t believe it. Well, not.

The only thing Alex proves is that he didn’t remotely understand what that MVP guy was (probably, I’m only guessing here, of course) talking about. The most important hint is one that Alex misses completely: The MVP said not to use exceptions, but instead use return codes… now, what might that have been about? The answer is simple, and it doesn’t take an MVP to tell anyone… a simple Google search says enough about this.

Exceptions are not a tool for flow control!

What does this mean? Simple, for example: If you are going to divide something by something else, it’s a much better idea to check the divisor for zero than to catch a DivideByZeroException. That’s what the MVP dude meant when he was talking about exceptions killing performance: it’s a simple processor instruction to check a variable for a specific value, it’ll take thousands of additional cycles to throw an exception and catch it, the result is the same.

An exception is meant as an instrument to signal that your application’s flow has been broken. That’s the one most important feature of the exception handling subsystem: it works across all boundaries of application flow. It’s neither designed nor very useful for any situation where the state of the application is known. Rule of thumb: if you expect that an error may occur in any specific line of code, and you are going to implement alternate handling for that particular case, don’t use an exception. That’s not an unexpected application state and shouldn’t be handled with an exception.

And then, if you’re going to measure executing speed, at least do it properly. Run a profiler and look at the number of method calls that take place in that small test program of yours. And then imagine, how fast would the .net framework be if some guys who work at MS didn’t know when (not) to use exceptions? Who says that your method is only ever going to be called ten times in a row? What’s your excuse why you didn’t write code that’s as fast as it can be? You laughed when someone tried to explain it to you?

Sorry, this blog does not support comments.

I used various blog hosting services since this blog was established in 2005, but unfortunately they turned out to be unreliable in the long term and comment threads were lost in unavoidable transitions. At this time I don't want to enable third-party services for comments since it has become obvious in recent years that these providers invariably monetize information about their visitors and users.

Please use the links in the page footer to get in touch with me. I'm available for conversations on Keybase, Matrix, Mastodon or Twitter, as well as via email.