Recoverable Runtime Errors
Learn about handling recoverable errors at runtime, using exceptions, and preserving the valid state of programs.
We'll cover the following...
Handling recoverable errors at runtime
If a function cannot uphold its part of the contract (the postcondition, that is), a runtime error has occurred and needs to be signaled to someplace in the code that can handle it and recover the valid state.
The purpose of handling recoverable errors is to pass an error from the place where the error occurred to the place where the valid state can be recovered. There are many ways to achieve this. There are two sides to this coin:
For the signaling part, we can choose between C++ exceptions, error codes, returning a
std::optional
orstd::pair
, or usingboost::outcome
orstd::experimental::expected
.Preserving the valid state of the program without leaking any resources. Deterministic destructors and automatic storage duration are the tools that make this possible in C++.
We will now focus on C++ exceptions and how to avoid leaking resources when recovering from an error.
Exceptions
Exceptions are the standard error handling mechanism provided by C++. The language was designed to be used with exceptions. One example of this is constructors that fail; the only way to signal errors from constructors is by using exceptions.
Exceptions can be used in many different ways. One reason for this is ...