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?
Edit To try and distinguish this more from past questions and be more concrete, suppose we have some library function that might throw a file not found exception. Some client code wants to use the library to access a file. The client code is being programmed with the expectation that the file sometimes will not exist, even under "unexceptional circumstances". The client code can be made able to check if the library function will throw an exception before being called but it's non-trivial to do so. Should client code pile additional error checking on top of the error checking within the library or should the client code use the library generated exception as control flow?
In such a case adding error handling code on top of the library will almost certainly be less efficient than catching an error, will require less coding, and it could be argued that you must have a try/catch anyway. On the other hand it is a decidedly unexceptional control flow mechanism.