c++linuxexceptiong++

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


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?


Solution

  • You need to catch it with char const* instead of char*. Neither anything like std::string nor char* will catch it.

    Catching has restricted rules with regard to what types it match. The spec says (where "cv" means "const/volatile combination" or neither of them).

    A handler is a match for an exception object of type E if

    • The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or
    • the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or
    • the handler is of type cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler by either or both of

      • a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes
      • a qualification conversion

    A string literal has type char const[N], but throwing an array will decay the array and actually throws a pointer to its first element. So you cannot catch a thrown string literal by a char*, because at the time it matches, it needs to match the char* to a char const*, which would throw away a const (a qualification conversion is only allowed to add const). The special conversion of a string literal to char* is only considered when you need to convert a string literal specifically.