user2601795
user2601795

Reputation: 71

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)

Upvotes: 7

Views: 1171

Answers (5)

Anand Rathi
Anand Rathi

Reputation: 786

Because you can implicitly assign a variable of less qualifier to more qualifier But you cant implicitly assign a variable of MORE qualifier to less qualifier

for example

foo(char * p)
fooc(const char * p)

int main(int argc, char agrv[]) {
  const char* cp = "hello";
  char* p = new char[10];
  foo(cp); // ==> compilation error
  strcpy(p,  cp);
  fooc(p) // No probs assigning to a more qualified var
}

Thats why @Joachim Pileborg is right :)

Upvotes: 2

thomas
thomas

Reputation: 525

It's not so simple. The question is showing something in C++. we can assign "const char*" literal to "char*"

char* ss = "full stack"; //ok, although "full stack" looks like a const char*

const char* s2 = "full stack";
char* ss = s2 ; //not ok

for take care of C program, C++ allow : char* ss = "full stack"; by the way. In my VS2005 complier, nothing happend( no coredump).

void main(){

    try
    {       
        throw "full stack";
    }
    catch (char *s)
    {
        std::cout << s <<std::endl;
    }
} 

Upvotes: 0

SteveLove
SteveLove

Reputation: 3207

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

Upvotes: 6

lulyon
lulyon

Reputation: 7255

Your try block throws a const type string: "full stack", which is not meant to be changed in your catch block.

In any case, const char * could not be implicitly casted to char *.

If the catch receive char *s parameter, the content that s point to might be changed by s[...] assignment, which is not acceptable, cause the content("full stack") is constant.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409356

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.

Upvotes: 9

Related Questions