【问题标题】:how to catch a general exception and show its derived what()如何捕获一般异常并显示其派生的 what()
【发布时间】:2013-01-15 20:42:44
【问题描述】:

这样的代码会出现问题:

#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;
}

我希望出现Message。但结果是std::exception。我认为可以从超类引用中调用子类virtual functions。如何解决?

【问题讨论】:

  • 你正在对异常对象进行切片

标签: c++ exception try-catch


【解决方案1】:

C++ 明确区分了引用和值副本。使用

catch (const std::exception& e) 

通过引用而不是值来捕获。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 2010-11-01
    • 2011-01-03
    • 2015-10-06
    相关资源
    最近更新 更多