how to catch a general exception and show its derived what()

天涯浪子 提交于 2019-12-24 03:47:07

问题


The problem happens with code like this:

#include <cstdlib>
#include <iostream>
#include <stdexcept>

using namespace std;

int main(int argc, char** argv) {

try {
    throw  runtime_error("Message");
} catch (exception e) {
    cout << e.what();
}
return 0;
}

I expect Message to appear. But the result was std::exception. I thought the subclass virtual functions can be called from the superclass reference. How can fix that?


回答1:


C++ makes an explicit distinction between reference and value copy. Use

catch (const std::exception& e) 

to catch by reference instead of value.



来源:https://stackoverflow.com/questions/14631011/how-to-catch-a-general-exception-and-show-its-derived-what

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!