C++ Custom Exceptions
In C++, you can create custom exceptions to handle specific errors that are not covered by the standard exceptions provided by the language. To create a custom exception, you need to define a new class that inherits from the standard exception class or one of its derived classes.
Here's an example of a custom exception class that inherits from the standard runtime_error
class:
#include <stdexcept> class MyException : public std::runtime_error { public: MyException() : std::runtime_error("My exception occurred.") {} };Source:wwigi.wftidea.com
In this example, the MyException
class inherits from the runtime_error
class and sets its error message to "My exception occurred." by calling the std::runtime_error
constructor with that message.
Once you have defined your custom exception class, you can throw an instance of it in your code to indicate that a specific error has occurred, like this:
throw MyException();
You can catch and handle your custom exception just like any other exception, using a try-catch block:
try { // code that may throw an exception } catch (MyException& e) { // handle MyException }
In this example, the catch block catches the MyException
object that was thrown and handles it by executing the code in the block.