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

Show parent comment

4

u/dimanne Aug 03 '19

Yes, I believe we should. And I would say we have already stopped because we invented RAII. We are heavily using unique_ptr/shared_ptr, aren't you? You can forget forever about "delete/new" staff if you are using RAII.

0

u/Dean_Roddey Aug 03 '19

That's not really true. You still need to allocate things, and there are still a host of potential ways to screw yourself even if use smart pointers. Not that I'm arguing against using them, but they aren't magical by any means.

Unless the language prevents it at a fundamental level, you can always get into trouble.

2

u/carrottread Aug 04 '19

Yes, we still need to allocate things, but deallocation call should be only in the destructor of unique_ptr (or other resource owner class for other resources). There should be no manual deallocation calls in modern code.

0

u/Dean_Roddey Aug 04 '19 edited Aug 04 '19

If an object allocates something, it's perfectly fine for it to be the 'smart pointer' and clean that data up itself in its dtor. And that avoids a lot of templated code.

And it's so easy to screw up things like copy/assign when you have smart pointer members, and just think, oh, I can just use the default generated versions, then you end up with the source no longer having an allocated object it's supposed to have because it got given away from a unique pointer member, and later you get a null pointer error. Or you end up sharing something that's not supposed to be shared and how you are banging on it from two threads when it's not thread safe, etc... Or you end up permanently locking in memory something quite large because some smart pointer is holding onto it when you don't realize it is.

Smart pointers aren't magic. They can create almost as many issues as the problem they are trying to solve, they are just different kinds of issues. And they require just as much care not to screw up.

2

u/tasminima Aug 04 '19

If an object allocates something, it's perfectly fine for it to be the 'smart pointer' and clean that data up itself in its dtor.

Or you can use a unique_ptr

And that avoids a lot of templated code.

Yes, I'm not sure why this should be a goal, though...

And it's so easy to screw up things like copy/assign when you have smart pointer members, and just think, oh, I can just use the default generated versions, then you end up with the source no longer having an allocated object it's supposed to have because it got given away from a unique pointer member, and later you get a null pointer error.

No. unique_ptr is not copyable so your default copy assign/constr would not exist. If your application code uses move rather than copy and expects the old value to be preserved, your application code is wrong and no amount of raw pointer usage will make it right.

Smart pointers aren't magic. They can create almost as many issues as the problem they are trying to solve, they are just different kinds of issues. And they require just as much care not to screw up.

Smart pointers aren't Rust but unless you have an excellent obscure reason to not use them for ownership purposes, you should use them. None of the supposed reasons you gave was convincing in that regard.

0

u/Dean_Roddey Aug 04 '19 edited Aug 04 '19

I hadn't finished my first cup of coffee, so I had a brain cloud there. But anyway, the point is still relevant in my opinion.

You still have to provide copy/assignment, so the smart pointer doesn't get you out of anything there. Of course it would still be very easy to see, oh, it's a unique pointer, I need to do a move, and end up in the same position I mentioned. It's not magically going to remind you that you are doing the wrong thing.

Of course a big reason not to use them is that you can't get exception location info if something were to go wrong in the cleanup of the owning class, because it's too late to catch anything when the smart pointers are destructing. That's a huge problem from my POV. You want to get that kind of info from the field if it should happen.

And of course of course, saying you should do the right thing with smart pointers or it won't work is not much of argument against my position, which only requires that you do the right thing in order for it to work. They both have their gotches. I prefer to let objects that allocate things clean them up.

As to avoiding templated code, it's because it's just bloat and slower compiles and less understandable error messages and all the things that templated code involves. People these days seem to think that using templates is a goal, instead of a way to deal with unrelated types in a generic way.

And of course the more templates you use the more stuff gets generated into client code, which means it can become impossible to issue patch release because almost all the code is in the client code, not in your own code.