I have a question regarding the following code snippet I came across in one of our older libraries.
try
{
throw "this is an error message";
}
catch( char* error )
{
cout << "an exception occured: " << error << endl;
}
My understanding of the behavior in this case is, that the error message is thrown by value, which means a copy of the text
“this is an error message”
is thrown. The catch clause specifies a pointer to char as expected type of exception. Can some enlighten me, why this works? Another question in this context concerns the memory allocated for the error message. Since the exception type is pointer to char* one could assume, that the memory for the error message has been allocated dynamically on the heap and has to be deleted by the user?
Thanks in advance
In
throwcontext arrays decay to pointers. And string literal is an array of characters. This means that:(1) What is “thrown by value” in this case is a
const char *pointer to the existing string literal. No copy of string literal is made. No additional memory is allocated by thisthrow. There’s no need to deallocate anything.(2) In order to catch this exception you need a
catch (const char *)handler. Yourchar *handler will not catch it, unless your compiler has a bug in it (this is a known persistent bug in MSVC++ compilers, which is not even fixed by/Zaoption).