C++ 中的异常不显示抛出到 cout

Exception in c++ not showing throw to cout

#include <iostream>

int main()
{
int num = 1;

try
{
    if (num != 0)
    {
        throw "num is not 0!";
    }
}
catch (char *x)
{
    cout << x << endl;
}
}

我希望此代码打印 "num is not 0!" 到 cout,但是当我 运行 它时,我得到 libc++abi.dylib: terminating with uncaught exception of type char const* Abort trap: 6 作为终端的输出。是我误解了异常的工作原理还是存在其他问题?

这是因为你抛出一个字符串字面值,它不能绑定到 char*。相反,它可以绑定到 char const*.

迂腐地,"num is not 0!" 的类型是 char const[14],然而,在 throw 表达式中 the array decays to a pointer 到它的第一个元素。