C++异常 - 抛出一个字符串

Jim*_*mmy 8 c++ error-handling exception-handling exception

我的代码遇到了一个小问题.出于某种原因,当我尝试使用下面的代码抛出一个字符串时,我在visual studio中出错了.

#include <string>
#include <iostream>
using namespace std;

int main()
{

    char input;

    cout << "\n\nWould you like to input? (y/n): ";
    cin >> input;
    input = tolower(input);

    try
    {
        if (input != 'y')
        {
            throw ("exception ! error");
        }
    }
    catch (string e)
    {
        cout << e << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

错误

链接:http://i.imgur.com/pYAXLuU.png

Mr.*_*C64 14

扔一根绳子真是个坏主意.

随意定义一个自定义异常类,并在其中嵌入一个字符串(或者只是从中派生自定义异常类std::runtime_error,将错误消息传递给构造函数,并使用该what()方法在catch-site获取错误字符串),但是千万不能丢一个字符串!

  • @ Mr.C64:那个页面解释了为什么抛出std :: runtime_exception的派生是有用的,并建议它"最好抛出对象,而不是内置函数",但它仍然没有解释抛出内置函数的坏处.插件. (3认同)
  • 我同意,扔掉与`std :: exception`无关的任何东西都是一个非常糟糕的主意...... (2认同)
  • 或者甚至只是抛出一个 `std::runtime_error('exception text')`。 (2认同)
  • 为什么?我很欣赏你的建议,但理由是什么? (2认同)

Syn*_*ose 12

你现在正在投掷一个const char*而不是一个std::string,而你应该投掷string("error")

编辑:错误已解决

throw string("exception ! error");
Run Code Online (Sandbox Code Playgroud)

  • @SyntacticFructose - 这很危险(按值抛出/捕获`std :: string`),因为必须构造一个字符串,这可能会引发错误.该字符串应该通过引用捕获. (3认同)