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:
#include <iostream> #include <exception> using namespace std; class MyException : public exception { public: char * what () { return "C++ Exception"; } }; int main() { try { throw MyException(); }catch(MyException e) { cout << "MyException caught" <<endl; cout << e.what() <<endl; } catch(exception e) { //Other errors } return 0; }
Output
MyException caught
C++ Exception
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
#include <iostream> #include <exception> using namespace std; class OverSpeed : public exception{ int speed; public : const char* what(){ return "check out ur car speed you are in the car not in an aeroplane "; } }; int main() { int carspeed=0; try { while(1) { carspeed+=10; if(carspeed>100) { OverSpeed s; throw s; } cout<<"Carspeed: "<<carspeed<<endl; } } catch(OverSpeed ex) { cout<<ex.what(); } return 0; }