Throw an exception object - C++ Statement

C++ examples for Statement:try catch

Description

Throw an exception object

Demo Code

#include <iostream>
#include <string>
using std::string;

class Trouble/*from  w w w.  j  ava2s  .c  o  m*/
{
private:
  string message;
public:
  Trouble(string str = "There's a problem") : message {str} {}
  string what() const { return message; }
};

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

Related Tutorials