Is there a general consensus in the C++ community

2020-02-08 03:20发布

问题:

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 6 years ago.

I just spent a few hours reading through SO questions on the topic of when to use exceptions, and it seems like there are two camps with different point of views:

  1. Use exceptions over error codes
  2. Use error codes most of the time, and exceptions only when some catastrophic error occurs

Is this just a controversial topic with no widely accepted best practice?

回答1:

As you can probably gather from the wealth of answers, there is certainly no consensus.

Semantically, exceptions and error provide the exact same functionality. Indeed they are identical in about all semantic aspects, and errors can be arbitrarily enriched much like exceptions (you don't have to use a simple code, you can use a real bundle of data!).

The only difference there is is their propagation methods:

  • errors have to be passed down manually
  • exceptions are propagated automatically

On the other hand:

  • the possibility of an error is perfectly documented in the signature
  • exceptions are silent on code inspection (read GotW #20: Code Complexity and cry) and hidden paths of execution make reasoning harder.

The very reason both solutions can appear clunky is simply that error checking is difficult. Indeed most of the code I am writing daily concerns error checking, whether technical or functional.

So what to do ?

Warning: demonstration ahead, jump over to the next section if you care only for an answer

I personally like to leverage the type system here. The typical example is the pointer-reference dichotomy: a pointer is like a reference that can be null (and reseated, but it does not matter here)

Therefore, instead of:

// Exceptions specifications are better not used in C++
// Those here are just to indicate the presence of exceptions
Object const& Container::search(Key const& key) const throw(NotFound);

I will tend to write:

Object const* Container::search(Key const& key) const;

Or better yet, using clever pointers:

Pointer<Object const> Container::search(Key const& key) const;

template <typename O>
O* Pointer<O>::operator->() const throw(Null);

template <typename O>
O& Pointer<O>::operator*() const throw(Null);

Here I find the use of exception superfluous for 2 reasons:

  • If we are searching for an object, then there not finding it is both a perfectly common occurrence and there is not much data to carry about: cause of error ? it is not there
  • The client does not necessarily consider it an error that it is not there, who am I to assume that I know her business better than she does ? Who am I to decide that there will never be a case where it won't be appropriate not to find what was asked for ?

I don't have a problem with exceptions per se, but they can make the code awkward, consider:

void noExceptions(Container const& c)
{
  Pointer<Object const> o = c.search("my-item");

  if (!o) {
    o = c.search("my-other-item");
  }

  if (!o) { return; } // nothing to be done

  // do something with o
}

And compare it with the "exception" case:

void exceptions(Container const& c)
{
  Object const* p = 0;
  try {
    p = &c.search("my-item");
  }
  catch(NotFound const&) {
    try {
      p = &c.search("my-other-item");
    }
    catch(NotFound const&) {
      return; // nothing to be done
    }
  }

  // do something with p
}

In this case, the use of exceptions does not seem appropriate :/

On the other hand:

try {
 print() << "My cute little baby " << baby.name() << " weighs " << baby.weight();
}
catch(Oupsie const&) {
  // deal
}

is certainly more appealing than:

if (!print("My cute little baby ")) { /*deal*/ }
if (!print(baby.name())) { /*deal*/ }
if (!print(" weighs ")) { /*deal*/ }
if (!print(baby.weight())) { /*deal*/ }

What is the best then ?

It depends. Like all engineering problem there is no silver bullet, it's all about concessions.

So keep 2 things in mind:

  • Error reporting is part of the API
  • APIs should be designed with ease of use in mind

If you find yourself wondering whether to use an exception or not, just try to use your API. If there is no clear cut winner, it is just that: there is no ideal solution.

Oh, and do not hesitate to refactor your API when it becomes clear that the error reporting mechanism elected at the time of crafting it is no longer appropriate. Don't be ashamed: requirements change with time, so it is normal that the API change with them.

Personally I tend to use exceptions for unrecoverable errors only: I therefore have few try/catch in my code, only in the outermost levels, to accurately log the error (love stack frames) and log a dump of the BOM as well.

This is very similar (and indeed strongly influenced) by Haskell, the code there is seggregated in two clear cut parts: while any can throw exceptions, only the IO part (the extern one) may actually catch them. Therefore, the pure part must deal with error conditions with other ways in case they are "normal".

If, however, I am faced with a problem where using an exception makes the code easier to read and more natural (which is subjective) then I use an exception :)



回答2:

I don't think this is a discussion which is exclusive to the C++ community, but here are two high-level guidelines which have helped me:

  1. Throw exceptions only in exceptional circumstances. It sounds obvious, but many APIs get built with exceptions being thrown about 50% of the time they are called (and a boolean return status would have been more appropriate).
  2. In your catch clauses, know when to consume exceptions, when to rethrow them as-is and when to throw a different type of exception instead. I can't give you a one-size-fits-all rule for this because it's so dependent on your application's needs, but if you take one thing away from this it should be that the silent consumption of an exception might be the worst thing your code could do. Each frame should have some knowledge of what the calling frame(s) expects when things go wrong.


回答3:

Exceptions are easier to use than error codes, because they can be thrown by an deeply nested subroutine and intercepted only at the level where it can be handled.

Error codes need to be passed up the chain so every function that calls another has to pass the error code back to its callers.

An error code doesn't have any clear functional advantages over exceptions since an exception can bundle an error code within it. There may have been a time when error codes might be more efficient than exceptions, but I think the cost of the extra code and the difficulty in maintaining it outweighs any possible advantage there.

However, error codes exist in many applications because they are written in, or were ported from, a language that didn't have exceptions, so it makes sense to keep using a uniform approach to error handling.



回答4:

No, there's no consensus, though.

Edit: As you can see, from the other answers, there's no consensus -- only schools of thought, principles of design, and plans of action. No plan is perfectly suited for every situation.



回答5:

Even if there were a common consensus, it wouldn't mean it is valid. Your primary consideration here should be the implementation and performance costs. These are both real constraints on the project and the resulting program. In this respect, here are some things to consider.

At runtime, exceptions are more expensive to propagate than simple return values. This is usually the source of the in exceptional cases argument. If you are throwing a lot of exceptions all the time you are suffering a performance penalty. Don't take this to mean exceptions are slow, they are still implemented very efficiently, but nonetheless costlier than error codes.

Exceptions can carry more information than error codes. Something like the boost::exception library allows tagged information which can provide a wealth of useful information up the chain of the exception. Unlike a simple error code saying file not found an exception can carry the filename, the module that tried to load it, and of course the underlying error code. This type of information is very hard to propagate via error codes up the stack.

Error code propagation can be cumbersome at implementation time. Any function that doesn't want to deal with an error has to pass the value up higher. Quite often you'll find code that simply ignores the error since the programmer couldn't deal with it at the time, or he didn't want to refactor his function signatures to pass along the error.

Exception catch syntax is bulky. It is often far easier to check a return code in an if statement than having to write a catch block. If a function has to catch too many differing exceptions at different points, the meaning of the code will be lost in a sea of braces and try/catch clauses. Here is the likely root of the notion that if a function call can normally fail a return code is likely better than an exception.

Understanding clearly how exceptions work will help you in making a decision. There are performance considerations but for many projects this will be negligible. There are concerns about exception safety, you have to know where it is safe and unsafe to use exceptions. Error codes also have the same safety concerns if people start doing short returns from functions.

Understanding the background of your team can also help out; consider if you have two new C++ programmers, one from a C background and the other coming from Java. Some people are more comfortable with error codes, others with exceptions. How far you push either in each direction will impact your project and contribute to the overall quality.

In the end there is no clear answer. While there are some situations where one may clearly win over the other, it highly depends on the project. Look at your code and continue to refactor when appropriate. Sometimes you won't even have an option as to what you use. Other times it'll make no difference. It is highly project specific.



回答6:

There is most certainly no consensus. At a high level, my mantra is that exceptions should be used in "exceptional cases" - that is, cases that are not a result of programmer error but of unpredictable conditions in the execution environment.

There are volumes of debate surrounding this issue. Depending on other practices in which you engage when writing programs - RAII for example - exceptions may become more or less idiomatically useful.



回答7:

Exceptions are the only way to properly report errors from a constructor, so the choice is clear there. Throwing an exception forces the caller to catch it and handle it somehow. The alternative design of an empty constructor with an init() method returning an error code is error prone and can lead to objects with an unknown state.



回答8:

The "C++ community" has factions, each of which has its own opinion about exceptions.

Where I work in the videogame industry, exceptions are forbidden in code that runs on a videogame system. This is because exceptions consume either CPU time OR memory, neither of which a videogame system has any to spare.

Also, in videogames there are few failure cases that warrant graceful recovery; If a videogame fails, human lives or property are not typically at stake.



回答9:

I like Boost's Error and Exception Handling guidelines. Basically, use exceptions when stack unwinding is desirable. This is simple and unambiguous.



回答10:

No consensus, but as the replies indicate, many people hold to the view to throw exceptinos only in exceptional circumstances. I don't much like that advice, because then the question becomes "what is an exceptional circumstance?". I prefer the following advice

A function must throw an exception if, and only if, the alternative would be failure to meet a post-condition (including all invariants as implicit post-conditions).

The implementation decision of whether to write throw in your code is then tied to the design decisions of the post-conditions for the function.

See C++ Coding Standards by Herb Sutter and Andrei Alexandrescu, items 70 (Distinguish between errors and non-errors) and 72 (Prefer to use exceptions to report errors).



回答11:

I did not see this addressed in any other replies, but (as described in the "Effective Java" book) when doing OOP, a possiblity to skip throwing exceptions is to have a helper method in an object to "ask" whether the operation to be done is possible.

For example the hasNext() method on Iterator or Scanner which is usually called before calling the corresponding next*() method.