Anti-patterns – Are Exceptions as Control Flow a Serious Antipattern?

anti-patternsexceptionsfinite-state machine

Back in the late 90's I worked quite a bit with a code base that used exceptions as flow control. It implemented a finite state machine to drive telephony applications. Lately I am reminded of those days because I've been doing MVC web apps.

They both have Controllers that decide where to go next and supply the data to the destination logic. User actions from the domain of an old-school telephone, like DTMF tones, became parameters to action methods, but instead of returning something like a ViewResult, they threw a StateTransitionException.

I think the main difference was that action methods were void functions. I don't remember all the things I did with this fact but I've been hesitant to even go down the road of remembering much because since that job, like 15 years ago, I never saw this in production code at any other job. I assumed this was a sign that it was a so-called anti-pattern.

Is this the case, and if so, why?

Update: when I asked the question, I already had @MasonWheeler's answer in mind so I went with the answer that added to my knowledge the most. I think his is a sound answer as well.

Best Answer

There's a detailed discussion of this on Ward's Wiki. Generally, the use of exceptions for control flow is an anti-pattern, with many notable situation - and language-specific (see for example Python) cough exceptions cough.

As a quick summary for why, generally, it's an anti-pattern:

  • Exceptions are, in essence, sophisticated GOTO statements
  • Programming with exceptions, therefore, leads to more difficult to read, and understand code
  • Most languages have existing control structures designed to solve your problems without the use of exceptions
  • Arguments for efficiency tend to be moot for modern compilers, which tend to optimize with the assumption that exceptions are not used for control flow.

Read the discussion at Ward's wiki for much more in-depth information.


See also a duplicate of this question, here

Related Topic