【发布时间】:2015-08-04 23:52:41
【问题描述】:
所以在参考手册中,what() 方法被描述为虚拟的,但它似乎并没有那样做。 (我正在用 g++ 和 c++11 标志编译)
#include <stdio.h> //printf
#include <iostream> //cout
#include <stdexcept>// std::invalid_argument
using namespace std;
void fn(){
throw runtime_error("wowwowo");
}
int main(){
try {fn(); }
catch(exception a) {cout << a.what() << endl;}
return 0;
}
输出是“std::exception”,而不是错误消息“wowwowo”。但是,如果我将 catch 类型更改为 runtime_error,它会按预期运行。我有一些代码,我想捕获可能是也可能不是 runtime_errors 的异常,我想我可以有多个 catch 块,但我很好奇为什么代码的行为如此。这是打印出错误消息的代码:
#include <stdio.h> //printf
#include <iostream> //cout
#include <stdexcept>// std::invalid_argument
using namespace std;
void fn(){
throw runtime_error("wowwowo");
}
int main(){
try {fn(); }
catch(runtime_error a) {cout << a.what() << endl;}
return 0;
}
【问题讨论】:
标签: c++ exception c++11 virtual