How to write a custom exception class in C++

Overview

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.

Example

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;
}

Explanation

  • 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.