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 a catch block? If I do not use it, I get this error:

 terminate called after throwing an instance of 'char const*' Aborted (core dumped) 
+7
c ++ exception-handling
source share
5 answers

Because you are throwing a string literal, and the string literal is the same as a pointer to read-only memory, so const is required.

+8
source share

In general, this is because your catch block will not catch the exception that you throw if you leave const.

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

You should still grab them using the const link to prevent copying and modifying the caught object (which is by no means useful):

 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. } 
+6
source share

Your try block produces a string of type const: "full stack", which is not intended to be modified in your catch block.

In any case, const char * cannot be implicitly entered into char *.

If the catch parameter receives the char * s parameter, then the contents that indicate can be changed by assigning s [...], which is unacceptable, which causes the content to persist ("full stack").

+2
source share

Because you can implicitly assign a variable of a lesser qualifier for more qualifiers. But you cannot implicitly assign a variable MORE for a lower qualifier

eg

 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 } 

This is why @Joachim Pileborg is right :)

+2
source share

It is not so easy. The question shows something in C ++. we can assign a const char * literal to a char *

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

to serve the program C, C ++ allow: char * ss = "full stack"; By the way. Nothing happened in my VS2005 compatible (no coredump).

 void main(){ try { throw "full stack"; } catch (char *s) { std::cout << s <<std::endl; } } 
0
source share

All Articles