What techniques can I use to avoid exceptions in C++, as mentioned in Google\'s style guide?
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.