try
{
if (isfull()==1)
throw "full stack";
else
a[top++] = x;
}
catch (const char *s)
{
cout<<s;
}
Why should we use const in the catch block? If I don't use it, I get this error:
terminate called after throwing an instance of 'char const*'
Aborted (core dumped)
Because you are throwing a string literal, and a string literal is the same as a pointer to constant memory, hence the need for const
.
More generally, it's because your catch block isn't catching the exception you're throwing, if you leave off the const.
However, throwing a non-exception type is considered bad form; consider throwing a std::runtime_error
or other type derived from std::exception. You can construct most of them with a string, and get the message from the what()
property.
You should still catch these by const reference, to prevent copying and modifying the caught object (which isn't a useful thing in any case):
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.
}
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