In the previous chapter we saw how to work with exception. In this chapter we shall see how to define our own exeption.
User defined exception might be useful in the case which are not pre defined in C++.
In such cases we should define our own exception.
We can create our own exceptions by inheriting the exception class and overriding its functionality to suite our needs.
Below is an example on how to create an user defined exception.
Example 1: Simple user defined exception
#include <iostream>
#include <mutex>
#include <thread>
// for more tutorial in C++ visit www.prodevelopertutorial.com
using namespace std;
class MyException : public exception
{
public:
char * what ()
{
return "Custom exception";
}
};
int main()
{
try
{
throw MyException();
}
catch(MyException e)
{
cout << "Custom exception has been caught" <<endl;
cout << e.what() <<endl;
}
catch(exception e)
{
//Other errors
}
return 0;
}
Output:
Custom exception has been caught
Custom exception
Throwing user defined exception
#include <iostream> // std::cout
// for more tutorials visit www.ProDeveloperTutorial.com
using namespace std;
class MyClass
{
};
int main()
{
try
{
throw MyClass();
}
catch (MyClass myObj)
{
cout << "MyClass exception caught \n";
}
}
Output:
MyClass exception caught