如何捕获一般的异常并显示其派生的what() [英] how to catch a general exception and show its derived what()
本文介绍了如何捕获一般的异常并显示其派生的what()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题发生在这样的代码:
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;
}
我希望消息
出现。但结果是 std :: exception
。我认为可以从超类引用调用子类虚函数
。怎么解决?
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?
推荐答案
C ++明确区分了reference和value copy。使用
C++ makes an explicit distinction between reference and value copy. Use
catch (const std::exception& e)
通过引用而不是值来捕捉。
to catch by reference instead of value.
这篇关于如何捕获一般的异常并显示其派生的what()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文