In the following program abort
method is called even when I have got the applicable catch statement. What is the reason?
#include <iostream>
#include <string>
using namespace std;
开发者_开发知识库
int main() {
try {
cout << "inside try\n";
throw "Text";
}
catch (string x) {
cout << "in catch" << x << endl;
}
cout << "Done with try-catch\n";
}
When I run the program I only get the first statement inside try
displayed and then I get this error:
Why does abort
get called even when I am handling string
exception?
Quite simple really!
You threw char const*
, but do not have a matching catch
for it.
Did you mean throw std::string("...");
?
Yes, you need to be catching a char const*, not an std::string!
Apart from what the other answers tell, as a general advice: Only throw what is derived from std::exception
, and if nothing else, in your top-handler, catch std::exception&
or const std::exception&
. This would have e.g. avoided this situation. See also
- C++ FAQ 17.2: What should I throw
- C++ FAQ 17.3: What should I catch
change type to char*
and it works as expected.
精彩评论