An important part of the book Learning C++ exception handling, and especially exception handling in C++ 20. Here is an example:
#include <strexcept>
#include <iostream>
class MyException : public std::runtime_error
{
public:
MyException(const char* message) : std::runtime_error(message) {}
/* a constructor for MyException that takes a message argument and passes it to the base class
constructor */
};
class MyClass
{
public:
void foo()
{
throw MyException("An error occurred in MyClass::foo()");
/* throw an instance of MyException with a custom message */
}
};
int main()
{
MyClass obj;
try
{
obj.foo(); // call MyClass::foo() inside a try block
}
catch (const std::exception& e)
{
std::cerr << "Exception caught: " << e.what() << std::endl;
/* catch any exception of type std::exception or its derived classes and print its error message to the
standard error stream */
}
return 0;
}