为什么我应该在catch块中使用"const"?

use*_*795 7 c++ exception-handling

try
{       
    if (isfull()==1)
        throw "full stack";
    else
        a[top++] = x;
}
catch (const char *s)
{
    cout<<s;
}
Run Code Online (Sandbox Code Playgroud)

我们为什么要在catch块中使用const?如果我不使用它,我会收到此错误:

terminate called after throwing an instance of 'char const*'  
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 8

因为你正在抛出一个字符串文字,而字符串文字与指向常量内存的指针相同,因此需要const.


Ste*_*ove 6

更一般地说,这是因为你的catch块没有捕获你抛出的异常,如果你不使用const.

但是,抛出非异常类型被认为是不好的形式; 考虑抛出std::runtime_error从std :: exception派生的一个或其他类型.您可以使用字符串构造其中的大多数,并从what()属性中获取消息.

您仍然应该通过const引用来捕获它们,以防止复制和修改捕获的对象(在任何情况下都不是有用的):

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.
}
Run Code Online (Sandbox Code Playgroud)