Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use "const" in my catch block?

try
{       
    if (isfull()==1)
        throw "full stack";
    else
        a[top++] = x;
}
catch (const char *s)
{
    cout<<s;
}

Why should we use const in the catch block? If I don't use it, I get this error:

terminate called after throwing an instance of 'char const*'  
Aborted (core dumped)
like image 885
user2601795 Avatar asked Jul 20 '13 08:07

user2601795


2 Answers

Because you are throwing a string literal, and a string literal is the same as a pointer to constant memory, hence the need for const.

like image 91
Some programmer dude Avatar answered Sep 28 '22 05:09

Some programmer dude


More generally, it's because your catch block isn't catching the exception you're throwing, if you leave off the const.

However, throwing a non-exception type is considered bad form; consider throwing a std::runtime_error or other type derived from std::exception. You can construct most of them with a string, and get the message from the what() property.

You should still catch these by const reference, to prevent copying and modifying the caught object (which isn't a useful thing in any case):

try
{
    throw runtime_error( "full stack" );
}
catch( const runtime_error & x )
{
    cout << x.what();
}
catch( const exception & x )
{
    // catch other exceptions derived from this base class.
}
like image 22
SteveLove Avatar answered Sep 28 '22 04:09

SteveLove