Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Whether error handling by throwing exceptions is good or bad is contentious. Are

ID: 658629 • Letter: W

Question

Whether error handling by throwing exceptions is good or bad is contentious.

Are exceptions as control flow considered a serious antipattern? If so, Why?

The common line is that exceptions are for "exceptional circumstances". But what if a library author has decided to throw an exception? The library author cannot predict what might be an "exceptional circumstance" for us.

Of course, if we cannot rule out an exception being thrown from a function that we must use as-is and permitting the exception to bubbling up to the top is unacceptable then we must catch the exception.

Often however, we can take preventative measures. With sufficient effort we might even be able to guarantee that the conditions under which the library function would throw an exception will never occur. The throw will still be there (it's not our choice) but we can eliminate the need for try and catch.

An example is std::map.at(). (Pretend there's no std::map.find().)

What is the general wisdom? Is it in good taste to write code with the expectation that a library function will occasionally throw? Is client code obligated to minimize the use of exceptions?

Explanation / Answer

The common line is that exceptions are for "exceptional circumstances".

Well, it's wrong.

Catching is certainly something you might want to do rarely, but exception throwing is not for exceptional circumstances at all. You should throw whenever a run-time condition means that you cannot fulfill your contract.

There's a big middle ground between "Using exceptions to replace if" and "Exceptions are only for exceptional circumstances".

Oh, and contracts that mean "Every caller must check for error every time", like return codes, are vastly worse than "Using exceptions to replace if".

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote