2 ms·
The reason why using exceptions for control flow is bad is because it violates the Samurai Principle. Now why do I refer to a cheesy made up principle instead o
by bjourne 14y ago
The reason why using exceptions for control flow is bad is because it
violates the Samurai Principle. Now why do I refer to a cheesy made up
principle instead of explaining what I mean? Why do people use
"exceptions are for exceptional situations" and similar empty
expressions?
Because programming is just as much about communicating intent as it
is about writing efficient code! Following guidelines and maxims is
extremely useful because if both the writer and the reader understands
the protocl, then communication is smoother.
The "Exceptions are for exceptional circumstances" protocol means that
the reader of the code doesn't have to wonder "Is this a control flow
situation? Is this exception supposed to be handled? Where does the
code resume?"
Following the Samurai Principle
(http://c2.com/cgi/wiki?SamuraiPrinciple http://c2.com/cgi/wiki?SamuraiPrinciple) similarily eases the
cognitive load of the person reading the code. It allows you to treat
each callable piece of code as an isolated unit whose value is equal
to what it returns. For non-critical code, you can completely forget
about exception handling because you dont need to bother. However, if
an exception is thrown you can be equally assured that something
unexpected happened. It was to hard for the "samurai function" to
handle. Simple and extremely convenient.
One example of not following the Samurai Principle or "exceptions for
exceptional situations" happened at my last job. We were an mobile
payment processor and trying to issue a charge to a customer when
their balance was to low would result in a
BalanceToLowException. Except that wasn't anything out of the
ordinary, customers would often not have enough funds! The situation
would be handled by retrying the transaction some other day. The API
for charging customers would better have been designed returning a two
tuple (chargeStatus,errorMsg) so that the following code could
continue in the same location whether the charge succeeded or
not. Throwing exceptions for ordinary events lead to spaghetti code.
You can see similar misdesigns in some database ORM:s in which some
queries throw silly NoRecordsFoundException which user code is forced
to handle. Or Python's classic
try: return int(somestr)
except ValueError: return None
Often the string you're passing to int() is user input so you expect
it to often be non-numeric.