所以在参考手册中,what()方法被描述为虚拟的,但它似乎并没有这样做。(我正在用c++和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,它的行为与预期一样。我有一些代码,我想捕获可能是或可能不是rununtime_errors的异常,我想我可以有多个捕获块,但我很好奇为什么代码的行为是这样的。下面是打印出错误消息的代码:
#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;
}
修改语句:
catch(exception a) {cout << a.what() << endl;}
:
catch(const exception &a) {cout << a.what() << endl;}
必须通过引用捕获异常,以便使其使用多态性。否则,您将对std::runtime_error
对象进行切片,因此只保留std::exception
对象,因此将调用std::exception::what()
而不是std::runtime_error::what()
。
至于函数本身,它确实是一个virtual
函数。
class exception {
public:
//...
virtual const char* what() const noexcept;
};