Using exceptions for error handling
Exceptions are responses to exceptional circumstances that can appear when a program is running. They enable the transfer of the control flow to another part of the program. Exceptions are a mechanism for simpler and more robust error handling, as opposed to returning error codes, which could greatly complicate and clutter the code. In this recipe, we will look at some key aspects related to throwing and handling exceptions.
Getting ready
This recipe requires you to have basic knowledge of the mechanisms of throwing exceptions (using the throw
statement) and catching exceptions (using try...catch
blocks). This recipe is focused on good practices around exceptions and not on the details of the exception mechanism in the C++ language.
How to do it...
Use the following practices to deal with exceptions:
- Throw exceptions by value:
void throwing_func() { throw std::runtime_error("timed out"); } void another_throwing_func...