For the following program:
int DivZero(int, int, int);
int main()
{
try {
cout << DivZero(1,0,2) << endl;
}
catch(char* e)
{
cout << "Exception is thrown!" << endl;
cout << e << endl;
return 1;
}
return 0;
}
int DivZero(int a, int b, int c)
{
if( a <= 0 || b <= 0 || c <= 0)
throw "All parameters must be greater than 0.";
return b/c + a;
}
Using char* e will give
terminate called after throwing an
instance of 'char const*'
According to C++ Exception Handling , the solution is to use const char* instead.
Further reading from function (const char *) vs. function (char *) said that
The type of "String" is
char*', not
const char*'
(this is a C discussion I think…)
Additional reading on Stack Overflow char* vs const char* as a parameter tells me the difference. But none of them address my questions:
- It seems like both char* and string* have limit on the numbers of characters. Am I correct?
- How does adding the keyword const to char* eliminates that limit? I thought the only purpose of const is to set a flag that said "unmodifiable". I understand that const char* e means " the pointer which points to unmodifiable char type".
The solution to that error is to use const char* e.
Even const string* e doesn't work. (just for the sake of testing…)
Can anyone explain, please? Thank you!
By the way, I am on Ubuntu, compiled by GCC, on Eclipse.
Best Answer
The email you linked to about "String" is wrong (and confusing).
Basically:
char*
is a pointer to an unbounded array of characters. Traditionally we consider such an array to be a C-string if it contains a set of valid characters followed by a\0
. There's no limit to the size of the array.const char*
is a pointer to an unbounded array of immutable characters.string*
is a pointer to astd::string
object, and is entirely different. This is a smart object that encapsulates a string. Usingstd::string
instead of C-strings can make your life loads easier, even though they've got some rough edges and a lot of nasty gotchas; they're well worth looking into, but they're not relevant to the question."String"
is a special expression that returns aconst char*
pointing at the specific C-string (note: this is not actually true, but it's a simplification that lets me answer the question concisely).A
char*
can be automatically cast to aconst char*
, but not vice versa. Note that old C++ compilers had a special exception to the type rules to let you do this:...without producing a type error; this was for C compatibility. Modern C++ compilers won't let you do it (such as recent gccs). They require this:
So. The problem here is that you've got:
...but then you're trying to catch it with:
This doesn't work, because the throw is throwing a
const char*
, which can't be cast to the type specified in the catch, so it isn't getting caught.This is why changing the catch to:
...makes it work.