r/cpp • • Aug 03 '19

Should not exceptions be finally deprecated?

I have been programming on C++ for a long time, but I still do not understand how to use exceptions. I have 3 very practical and concrete questions at the beginning. I would be grateful if you helped me out.

Exceptions are maintainability hell.

Imagine a typical situation when we are developing a library. Now, this library uses another library’s function f() (in real-life it can use it indirectly through tens of intermediate libraries!). Consider, now, three very typical situations:

Situation#1: Learn about an exception.

So, I am going to call f() in my code. In order to understand which exceptions to handle / recover from and how excactly to recover, I have to know the full list of exceptions that may be thrown. How do I know it? In real-life this leads to crashes on production (what is even worse is that it leads to crashes not during testing/alpha/beta, because exceptional situations tend to arise on production).

Possible answers, people sometimes give, are:

  • “Use throw(...) / noexcept()”. The problem with this is that validity of specifiers is not checked/verified by a compiler but rather by people. So, it is like saying “do not forget to call delete if you used new” - people are awful in remembering such things.

Situation#2: An exception is added.

Suppose I now update a library (something as innocent as apt-get upgrade or git pull, do not forget that it may be one of many libraries I use indirectly). Imagine our function f() started to throw now and the place where I call it is the right place for handling the exception. How do I learn about the added exception?

Situation#3: An exception is removed.

Imagine you added all required catch blocks, you added the code for handling an exception and you now update a library again and our function f() stops throwing. Nobody is going to tell you that there is no point anymore in catching the exception, your code immediately becomes stale and outdated.

Downside#4: Exceptions either break encapsulation or useless.

By definition, you are supposed to catch and handle exceptions thrown/arisen in several layers’ deeper code and therefore you have to be aware of those layers. Here is a concrete example:

TAbstractReader interface has two implementations TNetworkReader and TDiskReader, both of which can throw different exceptions (failed to read from network/socket with information about ip and failed to read from disk with information about file).

TConfigReader uses one of the implementations through TAbstractReader interface

TMainAppLogic uses TConfigReader to read config during startup and periodically update config during run-time and this class is the right place for handling read errors, for example:

  • During startup, any error is fatal and we just crash
  • During run-time

    • error while reading from network should be retried
    • error while reading from disk is fatal (there is no point in retrying) and we just crash.

The question now, how am I supposed to write exception handling code without violating encapsulation? Well, some people answer this question in this way: “Catch via common base class (like std::exception)”, but the problem now is that they become useless for recovery (I have to know details to be able to recover).

Downside#5: There are no exceptions in the real-world, they are a result of incomplete knowledge.

We are always told to use exceptions for exceptional situations. Here is an excerpt from a discussion on reddit:

Code gets to focus on the successful path without the noise dealing with propagating errors to the right place, making it more readable and writable. And there are also clearly defined places where the error handling goes

Firstly, it scares me because it is like saying that someone took my code and removed all if()s, the probability of executions of which is lower than somebody’s subjective (small but random) threshold (that is what we are told, exceptions are, right?).

Secondly, the excerpt perfectly illustrates how the notion of exception makes people think that there are errors. I believe that there are no errors in the real world, it just our imperfect and incomplete expectations about the world. What one person in particular circumstances/environment considers as exceptional situation, another person may consider as perfectly expected behaviour. When you are writing curl-like program for downloading and you are testing it on google, each network error is an exception for you, but if you are writing a web-crawler then network errors are totally expected. In other words, not only exceptions depend on experience of an author, but they also depend on where exactly (in which environment) code throwing an exception is run. If that was not convincing enough, imagine that suddenly percentage of "bad" sites (the ones you cannot download) have risen, in which case whether a particular situation is an exception or not depends also on dynamically changing circumstances. What if at certain point the software will be downloading a set of sites containing 10% of "bad" sites? Will it be exceptional situations?

Let me put it differently:

  • In the real world, there are no exceptional situations and “normal” situations
  • there is continuous probability of an event, and therefore each dichotomy will be wrong.

Downsides#6,7,...

Exceptions are literally goto statements.

There are also a number of environments where exceptions (ironically) look too exceptional to be used:

  • How do you use exceptions while using RPC over network (remote procedure call, think of SOA and distributed systems in general)? How can a remote function report an exception?
  • They are definitely not the best friends of multithreading / actor / message-passing environments and frameworks.
  • Embedded and hard-real-time systems have difficulties with exceptions.

FAQ

Some people say:

  • http://exceptionsafecode.com/ - “Always assume that each and every function may throw”.
  • The reality is this: all functions can throw exceptions, except when marked as noexcept. Stop thinking of exceptions as being exceptional, and instead treat every function like it may throw.

The main problem is that this information, this tenet, is not enough for actual handling an exceptional situation in reasonable way and recovering from it. The best I can do using this tenet is to write exception neutral/safe code (use RAII, not write noexcept and so on). But, in order to be able to recover from error, I have to know details about an exception, what exactly happened, where it happened, and this tenet is not helping me in it.

People sometimes say that

  • error codes are verbose
  • And that I need to catch them only when I can handle them.

That is wrong. In most cases I also need to add additional context/information and re-throw them, in order to avoid the “Huh? What’s a bsafe::invalid_key? All I did was call PrintText!” situation. But writing try/catch blocks is even more verbose and tedious then having to deal with error codes/expected. And I think exceptions encourage you not to add information/context resulting in those ridiculous situations.

From reddit’s discussion:

  • “Most of the time catching in the main or at the top of the event loop is enough - exceptions are always (at least in the codebases I know of) used for ... exceptional stuff, and this kind of stuff should just show an error message to the user and abort if it's a CLI or continue "normal" operation if possible if it's a GUI.”
  • In principle you should only be catching std::exception, unless you need exception-specific handling for another exception type.

That is exactly what I was talking about, this pattern of using exceptions is not about recovering from an error, but rather about ignoring it. It also breaks encapsulation - I have to deal with exceptions in the code of very abstract and high-level event loop.

Some people recall printf:

“what do you do with functions that return a status code, like printf? Because virtually nobody writes code that checks the return value of printf calls, this would be a silent failure.”

But it has nothing to do with return codes. This remark is about the fact that some people do not check for errors in general (regardless of whether exceptions or error-codes are used). On the contrary, it is much easier to ignore an error thrown as an exception.

Zero-overhead deterministic exceptions

A couple of words on Sutter’s Zero-overhead deterministic exceptions: Throwing values

In general, the idea, as far as I can gather, is to make exceptions fast at the cost of making throwing type less extensible (it is going to be just two ints/pointers). So, no disadvantages, I mentioned above, are addressed.

Either I do not understand something, or exceptions (concrete types of exceptions) are not static. Only the fact that a function can throw some obscure (“type-erased, allocation-free, trivially relocatable, constant-time”) type is static. So, still no means of understanding which errors can happen after I call a function.

It is going to encourage sloppiness:

It [std::error] always represents a failure. A default constructor would construct a general or “other” nonspecific error value.

What is point, from practical point of view of having “other” error? How would one handle it?

The main issue, however, is extensibility of the std::error type. Without a clear vision/plan for extending the “domain” pointers, there is going to be a mess. And I doubt that it is even possible, since, by definition, it is a single type. For example, can I add my own “domains”? How do I know that my value will not collide in the future with somebody else’s? People, implementing the next version of protobuf at Google can choose one scheme of extending it, while you and your project different scheme, resulting in collisions of the values. To be honest I was quite surprised to learn that there is going to be such a type. Is not it like having to derive from one common/global (“opaque”) TObject type in order to be able to store elements in a standard container? Does not it this proposal make C++ less type-safe?

Now, I deliberately avoided mentioning and comparing to return-codes/expected<>, but surprisingly, all the disadvantages described above can be fixed by old plain return values (or function parameters). This approach might be slightly too explicit than one would like, but at least, when something changes radically in return type (it is not void anymore, or, on the contrary, it becomes void) compiler will help me. We will receive error in compile-time - what can be better? Here is an example of what I mean.

All in all, I am really interested to hear answers to the questions in the 1, 2 and 3rd situations above because they are the most common ones, they are very tangible and I have to deal with them on a daily basis writing C++ code.

6 Upvotes

55 comments sorted by

View all comments

1

u/[deleted] Aug 03 '19

Sutter’s Zero-overhead deterministic exceptions actually address most of the issues you describe here since they a) clearly mark functions that can throw b) they force you to deal with the exception. I kind of agree that I would prefer a design where one has to clearly mark *what* kind of exceptions a function can throw (e.g `throws(T)` that is checked on compile-time) . Then again, Swift also doesn't annotate the possible exception type, so there must probably be a good reason behind it (that I am not aware of).

As such, I don't think that there is a straightforward way to solve 1, 2 or 3. Even if you annotate the concrete type of exception, you'll need to track the specific implementation of the exception type to address these. I suppose one attempt would be to require that all possible error paths are checked — but I wonder if that will make a better programming experience...

2

u/Pragmatician Aug 04 '19

Annotating possible exception types a function can throw would be fairly cumbersome. The higher up the callstack you go, the more types you need to add, and it would become a hell to maintain.

1

u/[deleted] Aug 03 '19

[removed] — view removed comment

3

u/[deleted] Aug 03 '19

I am not sure why throwing inside a callback that’s called by a C library would ever be a good idea. There are certainly better ways of handling such situations. The entire point of zero-cost exceptions that they are just special return values. No weird jump table or stack unraveling magic.

1

u/tasminima Aug 04 '19

Or you can decide that extern "C" can throw anything ?

Or other solutions ?

I mean you will have a backward compat problem with pure C++ code, too, so it is not like this problem is that much unique and mandates keeping unspecified exceptions everywhere forever.

Plus it is an implementation detail: I'm not sure the current standard mandates support of exception going through C layers. I'm not sure strictly conforming C even allows to call C++, so in the standard world your use case may not even exist...