Custom C++ exception class creation

  Pi Ke        2012-03-04 09:58:18       31,847        2    

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++  STD  EXCEPTION  CUSTOM EXCEPTION  IMPLEMENTATION 

       

  RELATED


  2 COMMENTS


Yoshi [Reply]@ 2012-12-21 04:51:13
In ~MyException9void); , it should be a '('. :)
Pi Ke [Reply]@ 2012-12-21 13:56:38
Thank you for pointing it out. I have modified it.


  RANDOM FUN

How do you know someone is a local