What type should I catch if I throw a string literal?

后端 未结 7 863
南笙
南笙 2020-12-05 18:11

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).

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 18:43

    The type of a string literal is char const *. There's a (deprecated) conversion to char * provided for backward compatibility with existing code (but you still have to treat it as const -- any attempt at modification gives UB).

    As such, code like this should work:

    #include 
    using namespace std;
    
    int main()
    {
      try
      {
        throw "not implemented";
    
      }
      catch(char const *error)
      {
        cerr<<"Error: "<

提交回复
热议问题