User Defined Exceptions in C++

In this tutorial we will study and understand how to create our own User Defined Exceptions in C++. For this you need to first understand the concept of exceptions and exception handling in C++.Also you need to know the concept of Classes and Inheritance in C++. Assuming that you already know these concepts, lets get started.

User Defined Exception in C++

There maybe situations where you want to generate some user/program specific exceptions which are not pre-defined in C++. In such cases C++ provided us with the mechanism to create our own exceptions by inheriting the exception class in C++ and overriding its functionality according to our needs. Let us see an example of user-defined exception:

Output
MyException caught
C++ Exception
Program Explanation
  • In order to create a user defined exception we first included the <exception> header using the pre-processor directive. This header has the base class exception which we have to inherit and override to create any user defined exceptions
  • In the next step we created a class named MyException and inherited all properties from the exception class. Then we created function what() which basically returns an error message string (in this case – C++ Exception). So whenever an exception of type MyException occurs, this message will be displayed. The return type of this function what() is char* because we are returning a character string.
  • In the last step, inside the main function we create a try{}…catch() block and inside the try block we create an object of MyException class and use the throw keyword to explicitly throw an exception using this object.
  • This Object is then caught in the catch block where we print out the message by accessing the what() function of this(MyException) class’s object.
User Defined Exception in C++ Sample Program

Run Online

Leave a Reply

Your email address will not be published. Required fields are marked *