Exception safety is the promise that a function makes about the state of the program when it returns or when it throws. And the noexcept specification is the promise that a function never throws at all. Both of them are things that you write in the signature, and the compiler uses them to generate better code and to make the standard library safer.
The previous lesson in this module covered "How Do Exceptions Propagate and Get Handled?", and the next lesson in this module is about "How Do assert and Error Codes Compare to Exceptions?".
The three guarantees
the guarantee what it means
------------------ ----------------------------------------------------
the nothrow the function never throws
the strong if it throws, the object is exactly as it was
the basic if it throws, the object is still valid, but it
may have changed
And the strong guarantee is the one that you usually want, because it means that a caller can simply retry or carry on without having to repair anything.
Copy and swap
The copy-and-swap is the standard technique for getting the strong guarantee, and it also removes the self-assignment problem.
#include <iostream>
#include <string>
#include <utility>
class Price {
public:
Price(int cents, const std::string& currency)
: cents_(cents), currency_(currency) {}
Price(const Price& other) = default;
Price& operator=(Price other) {
swap(other);
return *this;
}
void swap(Price& other) noexcept {
std::swap(cents_, other.cents_);
std::swap(currency_, other.currency_);
}
int cents() const { return cents_; }
private:
int cents_;
std::string currency_;
};
int main() {
Price first(100, "GBP");
Price second(250, "GBP");
first = second; // copy, then swap
std::cout << "first: " << first.cents() << '\n';
first = first; // self-assignment is safe
std::cout << "still: " << first.cents() << '\n';
return 0;
}The output shows both the assignment and the self-assignment working.
first: 250
still: 250And the way that it works is simple. The parameter is taken by value, so the copy happens before anything is changed. Then the swap exchanges the contents, and the temporary cleans up the old value. If the copy throws then nothing has been changed at all.
What noexcept means
The noexcept is not decorative. The compiler uses the promise to generate the better code, and the standard library uses it to decide whether a container can move the elements during a reallocation.
#include <iostream>
#include <string>
#include <utility>
void may_throw() {
throw std::runtime_error("something went wrong");
}
int main() {
try {
may_throw();
} catch (const std::exception& error) {
std::cout << "caught: " << error.what() << '\n';
}
std::cout << "noexcept(int) is " << std::boolalpha << noexcept(1 + 1) << '\n';
std::cout << "noexcept(may_throw) is " << noexcept(may_throw) << '\n';
return 0;
}The output shows the operator reporting whether an expression can throw.
caught: something went wrong
noexcept(int) is true
noexcept(may_throw) is trueAnd if a function that is marked as noexcept does throw, then the program calls the std::terminate and it dies immediately, which is much harder to debug than an ordinary exception.
#include <iostream>
#include <stdexcept>
void dangerous() noexcept {
throw std::runtime_error("this terminates the program");
}
int main() {
std::cout << "before\n";
try {
dangerous();
} catch (...) {
std::cout << "never printed\n";
}
return 0;
}When noexcept is right
There are three places where you should write it. The first one is the move constructor and the move assignment operator, because the containers need to know that the move cannot throw. The second one is the destructor, because the destructor runs during the unwinding and a throw there would be a disaster. And the third one is any function that genuinely cannot throw, such as a simple getter.
The basic guarantee in practice
And here is the basic guarantee in practice. The first update might succeed and the second one might throw, and then the object is in a state that is valid but not the state that the caller expected.
#include <iostream>
#include <stdexcept>
#include <string>
class Settings {
public:
void apply(const std::string& name, int value) {
name_ = name; // if this throws, nothing changed
value_ = value; // if this throws, the name changed
}
void apply_safely(const std::string& name, int value) {
Settings copy = *this; // work on a copy
copy.name_ = name;
copy.value_ = value;
*this = std::move(copy); // commit only if everything worked
}
const std::string& name() const { return name_; }
int value() const { return value_; }
private:
std::string name_;
int value_ = 0;
};
int main() {
Settings settings;
settings.apply_safely("threshold", 42);
std::cout << settings.name() << '=' << settings.value() << '\n';
return 0;
}The output shows the safe version committing the change.
threshold=42Quick reference
- The nothrow guarantee means that the function never throws.
- The strong guarantee means that a throw leaves the object exactly as it was.
- The basic guarantee means that a throw leaves the object valid, but it may have changed.
- The copy-and-swap gives you the strong guarantee and it handles the self-assignment.
- You mark the move operations and the destructors as
noexcept. - A throw from a
noexceptfunction calls thestd::terminateand it kills the program.
Try it yourself: write a class with two fields and a method that sets both of them, and make one of the assignments throw. Show that the object is left in a half-updated state, and then change the method to use the copy-and-swap so that the object is never changed when it throws.