Home > Software engineering >  Throw and Catch in c
Throw and Catch in c

Time:08-28

(c )So my throw code is like throw "No paper" And my catch code is catch(const char *txt ){} My question is why we are using a pointer to define the catch type and why char, can't we use something like catch(string txt){} I just learn exception handling and can't figure out why they used a pointer. here is the code!

CodePudding user response:

When you throw a C string literal like "No paper" you are actually throwing a pointer of type const char* and not an array of characters. This is how C works.

In other words, a string literal automatically decays into a const char*. It doesn't magically turn into a std::string or something like that when the catch parameter receives it.

And technically speaking, it's usually more efficient to throw an 8 byte pointer rather than to throw a 32 byte std::string. The bigger the size of an object is, the more costly it is to copy it around during the exception handling process.

  • Related