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

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

terminate called after throwing an instance of 'char const*'  
Aborted (core dumped)
4

5 回答 5

9

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

于 2013-07-20T08:10:19.553 回答
6

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

但是,抛出非异常类型被认为是错误的形式;考虑抛出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.
}
于 2013-07-20T08:24:50.840 回答
2

因为你可以隐式地将一个更少限定符的变量分配给更多限定符但是你不能将一个更多限定符的变量隐式分配给更少限定符

例如

foo(char * p)
fooc(const char * p)

int main(int argc, char agrv[]) {
  const char* cp = "hello";
  char* p = new char[10];
  foo(cp); // ==> compilation error
  strcpy(p,  cp);
  fooc(p) // No probs assigning to a more qualified var
}

这就是为什么@Joachim Pileborg 是对的:)

于 2013-07-20T08:27:37.397 回答
2

您的 try 块会抛出一个 const 类型的字符串:“full stack”,这并不意味着在您的 catch 块中进行更改。

在任何情况下,const char * 都不能隐式转换为 char *。

如果 catch 接收到 char *s 参数,s 指向的内容可能会被 s[...] 赋值改变,这是不可接受的,因为 content("full stack") 是常量。

于 2013-07-20T08:11:47.997 回答
0

这不是那么简单。问题是在 C++ 中显示一些东西。我们可以将“const char*”文字分配给“char*”

char* ss = "full stack"; //ok, although "full stack" looks like a const char*

const char* s2 = "full stack";
char* ss = s2 ; //not ok

为了照顾 C 程序,C++ 允许: char* ss = "full stack"; 顺便一提。在我的 VS2005 编译器中,什么也没发生(没有核心转储)。

void main(){

    try
    {       
        throw "full stack";
    }
    catch (char *s)
    {
        std::cout << s <<std::endl;
    }
} 
于 2013-07-20T10:05:30.897 回答