Custom C++ exception class creation

Summary

C++ offers built-in exception handling using `try-catch` blocks and standard exception classes from `#include `. For more specific error management, developers can define custom exception classes by inheriting from `std::exception`. This process involves implementing a constructor, which can accept a custom error message, and overriding the virtual `what()` method to return a descriptive C-style string. Custom exceptions are then thrown using `throw` and caught by reference in a `catch` block, enabling tailored error reporting and improved debugging.

In standard C++, we can use try catch to catch and exception when something goes wrong. These are some built in exception support in C++. By including the #include , we can now catch exceptions in C++ programs. This actually helps us on debugging our code and reduce the maintenance work.

However sometimes if we want to create our own custom exception class. What should we do?

We should include the #include line and then extend the exception class and implement some methods as you like. The general format is :

#include
using namespace std;
class MyException:public exception{
public:
          MyException(const string m="my custom exception"):msg(m){}
          ~MyException(void);
          const char* what(){return msg.c_str();}
private:
           string msg;
};

Here we can pass an error message to the constructor and if you don;t specify the error message when create MyException object, the "my custom exception" will be the default error message. Also, the what() method is to tell the program what exception it is.

We can use it as :
#include
using namespace std;
int main(){
          try{
               throw MyException();
          }catch(MyException& e){
               cout<<e.what()<<endl;
          }
          return 0;
}

C++ IMPLEMENTATION STD EXCEPTION CUSTOM EXCEPTION

  RELATED

  COMMENTS

2
Yoshi
Dec 21, 2012 at 4:51 am
In ~MyException9void); , it should be a '('. :)
Pi Ke
Dec 21, 2012 at 1:56 pm
Thank you for pointing it out. I have modified it.