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*', notconst 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.
Why are you throwing and catching strings anyway?
You should throw and catch exceptions, e.g.
std::runtime_errorThe answer to your question is that whenever you insert a string in quotes in the code it returns a null terminated const char*
The reason your code doesn’t work as above is because it’s the wrong type, so that catch, isn’t catching what you’re throwing. You’re throwing a const char*.
There is no limit to the number of characters in a char array beyond the size of your stack/heap. If you’re referring to the example you posted, that person had created a fixed size array, so they were limited.