I am trying to catch a char * type exception in main() but the program crashes with the following message: terminate called after throwing an instance of 'char const*' Here is the code:
#include <iostream>
int main ()
{
char myarray[10];
try
{
for (int n=0; n<=10; n++)
{
if (n>9)
throw "Out of range";
myarray[n]='a';
}
}
catch (char * str)
{
std::cout << "Exception: " << str << std::endl;
}
return 0;
}
Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.
It uses a long jump out of the current function to the try block. The try block then uses an if/else to skip the code block to the catch block which check the local variable to see if it should catch. This uses a global pointer so the longjmp() knows what try was last run.
The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.
If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.
Use const:
catch (const char * str)
{
std::cout << "Exception: " << str << std::endl;
}
You don't want to catch char*
.
I don't know where this idea comes from that string literals are char*
: they're not.
String literals are const char[N]
which decays to const char*
.
Catch const char*
.
Your program is being terminated because, at present, you're actually not handling your exception!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With