C++ exception — 02
Date: 2023-01-09Last modified: 2023-12-22
Table of contents
Strong and weak exception guarantee
When writing any C++ code, we have essentially four options regarding exceptions:
- we can completely ignore exceptions (no exception guarantee)
- we can guarantee that our code does not throw exceptions (noexcept)
- we can guarantee that if our code throws, it doesn’t violate any invariants (weak exception guarantee)
- we can guarantee that if our code throws, the state doesn’t change (strong exception guarantee)
The strong exception guarantee is effectively transactional. Either the operation succeeds, or nothing changes.
The weak exception guarantee permits partial changes (that do not violate invariants).
This topic is complex, and was divided into several parts.
#include <fmt/core.h>
void uh_oh() noexcept {
fmt::print("uh_oh() called\n");
throw 1;
}
int main() {
try {
uh_oh(); // 💩 this program will abort here.
} catch (const int &e) {
fmt::print("The exception was thrown\n"); // 💩 not called!
} catch (...) {
fmt::print("Unknown exception\n"); // 💩 not called!
}
return 0;
}
Compilation warning:
exception_02.cpp:5:3: warning: 'uh_oh' has a non-throwing exception specification but can still throw [-Wexceptions]
5 | throw 1;
| ^
exception_02.cpp:3:6: note: function declared non-throwing here
3 | void uh_oh() noexcept {
| ^ ~~~~~~~~
1 warning generated.
Possible output
stdout:
stderr:
terminate called after throwing an instance of 'int'
Makefile: Failure on bin/exception_02 execution