What type should I catch if I throw a string liter

2019-01-23 02:37发布

I am writing a pretty simple application in C++ using g++ under Linux and I am trying to throw some raw strings as exceptions (yes, I know, its not a good practise).

I have the following code (simplified):

int main()
{
  try
  {
    throw "not implemented";

  }
  catch(std::string &error)
  {
    cerr<<"Error: "<<error<<endl;
  }
  catch(char* error)
  {
    cerr<<"Error: "<<error<<endl;
  }
  catch(...)
  {
    cerr<<"Unknown error"<<endl;
  }
}

And I get Unknow error on the console. But if I static cast the literal string to either std::string or char * it prints Error: not implemented as expected. My question is: so what is the type I should catch if I don't want to use static casts?

7条回答
放荡不羁爱自由
2楼-- · 2019-01-23 03:24

The type should be const char[15] or const char*.

However, while the language does not forbids you throwing any type value, you should not be raising native data types as exception. Instead, you want to raise an std::exception() instance, or creating your own exception class.

查看更多
登录 后发表回答