为什么三元操作失败不能尝试捕获

dev*_*bug 3 c++ exception try-catch ternary-operator

我在这里指的是代码.然后我修改它如下,以捕获失败.但代码失败而没有捕获异常.如何处理(捕获)此故障?

#include <iostream>
#include <exception>
using namespace std;

int main()
{
int test = 0;
cout << "test set to 0" << endl;
try {
    cout << (test ? "A String" : 0) << endl;
} catch(...) {
    cout << "Exception" << endl;
}
cout << "Test done" << endl;

return 0;
}
Run Code Online (Sandbox Code Playgroud)

Kal*_*drr 5

你的代码不会抛出任何异常,类型"A String"const char*,所以一个指针,并且0可以被评估为NULL一个指针,这意味着test ? "A String" : 0返回const char*,没有错误.

此外,我不认为您知道异常如何工作,如果您的代码有错误 test ? std::string{"A String"} : nullptr,该错误将是编译时错误,而不是异常,因为编译器将无法找到这两种类型的公共类型.