Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid using exceptions in C++?

Tags:

c++

exception

What techniques can I use to avoid exceptions in C++, as mentioned in Google's style guide?

like image 494
yesraaj Avatar asked Dec 04 '22 14:12

yesraaj


2 Answers

  1. Don't throw exceptions.
  2. Don't use STL (which relies heavily on exceptions).
  3. Use only new(std::nothrow) or override ::operator new to return 0 on failure.

Note that by avoiding exceptions, you're effectively throwing out lots of useful libraries, including Boost. Basically, you'll have to program everything from scratch.

like image 82
avakar Avatar answered Dec 09 '22 15:12

avakar


Not throwing exceptions in your own code is relatively easy: you just don't use the throw statement.

Not throwing exceptions from memory allocation failures is a little more painful: either you don't use normal new (use new(std::nothrow) or malloc or something instead), or you use some nonstandard compiler option to get it to do something nonstandard when it fails (e.g. immediately terminate your program, or return 0), or you override operator new to do something nonstandard when it fails.

If your chosen approach is to immediately terminate the program, you can implement this with set_new_handler(), which I had forgotten about until litb reminded me.

That leaves the problem of dealing with exceptions generated by C++ libraries you don't maintain. Generally you'll have to wrap library calls in a wrapper that looks something like this:

int DoSomething(int &output, const int input) throw() {
  try {
    output = library_do_something(input);
    return 1;
  } catch (...) {
    return 0;
  }
}

The catch (...) catches all possible C++ exceptions from library_do_something (as well as the assignment operator on output, which isn't relevant here), throws away all the information they may have contained, and then maps all those failures to 0.

Note that this style means that you can't use RAII at all, not even a little bit, because you have no way of signaling failure within a constructor. The whole point of RAII is that you acquire all your resources inside of constructors so that they will be properly released by a destructor during exception propagation. But resource acquisition is something that can essentially always fail. So you can't do that inside a constructor.

like image 34
Kragen Javier Sitaker Avatar answered Dec 09 '22 14:12

Kragen Javier Sitaker