问题
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