开发者

why is abort method called?

开发者 https://www.devze.com 2023-03-17 04:03 出处:网络
In the following program abort method is called even when I have got the applicable catch statement. What is the reason?

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 is abort method called?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消