Throw a custom exception object : Custom Exception « Exceptions « C++ Tutorial






#include <iostream>

using std::cout;
using std::endl;

class Trouble {
  public:
    Trouble(const char* pStr = "There's a problem") : pMessage(pStr) {}
    const char* what() const {return pMessage;}

  private:
    const char* pMessage;
};

int main() {
  for(int i = 0 ; i < 2 ; i++) {
    try     {
      if(i == 0)
        throw Trouble();
      else
        throw Trouble("Nobody knows the trouble I've seen...");
    }
    catch(const Trouble& t) {
      cout << endl << "Exception: " << t.what();
    }
  }
  return 0;
}
Exception: There's a problem
Exception: Nobody knows the trouble I've seen..."








6.5.Custom Exception
6.5.1.Throw your own exception class based on runtime_error
6.5.2.Custom exception class
6.5.3.Throw a custom exception object
6.5.4.Use custom exception in your own Array class