我有一个C++程序,不能简单
#include <string>
#include <iostream>
using namespace std;
void throwE(){
throw "ERROR";
}
int main(int argc, char* argv[]){
try{
throwE();
} catch(const std::string& msg){
cerr << msg << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但它在运行时会引发异常:
libc++abi.dylib: terminate called throwing an exception
Abort trap: 6
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉我为什么会发生这种情况,为什么没有发现异常?
你没有抛出一个std::string,但是一个nul终止的字符串(类型"ERROR" is really const char[6]和throw表达式衰减到const char*.).所以你没有抓住异常.如果你改变throwE为抛出一个std::string,它按预期工作:
void throwE(){
throw std::string("ERROR");
}
Run Code Online (Sandbox Code Playgroud)
或者,捕获a const char*,它与const char[6]衰减后抛出的异常类型相匹配const char*:
} catch(const char* msg){
cerr << msg << endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
错误
| 归档时间: |
|
| 查看次数: |
114 次 |
| 最近记录: |