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?
The type should be
const char[15]
orconst 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.