The standard library of C++ provides users with the base class, which is specifically designed to declare the objects that used to be thrown as exceptions. The base class is defined in the <exception> header file and is called as std:exception. This class contains a virtual member method, which produces a null-terminated character sequence (of type char *) that may be rewritten in derived classes to provide an exception explanation.
Letβs look at a basic example to better understand this concept.
#include <iostream>#include <exception>using namespace std;class myexception: public exception{virtual const char* what() const throw(){return "Custom Exception";}};int main (){myexception ex;try{throw ex;}catch (exception& except){cout << except.what() << endl;}return 0;}
Lines 1β3: We import the header files.
Lines 5β11: We make a user-defined exception class and inherit it from the except class. We use the virtual function to overload the what() function and return the exception.
Line 13: We write the main driver for the program.
Line 15: We make the object of the myexception class.
Lines 16β23: We use the try and catch statements to throw and then catch the statements, so that we can display the written message.