January 2020
Intermediate to advanced
454 pages
11h 25m
English
Creating your own C++ exceptions allows you to filter out what type of exception you are getting. For example, did the exception come from your code or the C++ library? By creating your own C++ exceptions, you can easily answer these questions during runtime in your own code. Let's look at the following example:
#include <iostream>#include <stdexcept>class the_answer : public std::exception{public: the_answer() = default; const char *what() const noexcept { return "The answer is: 42"; }};int main(void){ try { throw the_answer{}; } catch (const std::exception &e) { std::cout << e.what() << '\n'; }}
As shown in the preceding example, we create our own C++ exception by inheriting std::exception. This is not a requirement. Technically, ...