【问题标题】:C++ Exception - Throw a StringC++ 异常 - 抛出一个字符串
【发布时间】:2015-01-26 13:02:44
【问题描述】:

我的代码有一个小问题。出于某种原因,当我尝试使用下面的代码抛出一个字符串时,我在 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;
    }
}

错误:

【问题讨论】:

  • 如果你想捕获一个字符串,抛出一个字符串而不是字符串文字。否则捕获一个 const char*。尽管使用其中一个异常类会更好。

标签: c++ exception error-handling


【解决方案1】:

抛出一个字符串确实是个坏主意。

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

【讨论】:

  • 我同意,扔任何与std::exception 无关的东西是个坏主意……
  • 或者甚至只是抛出一个std::runtime_error('exception text')
  • 为什么?我很欣赏这个建议,但原因是什么?
  • @feuGene 你可能想看看this C++ FAQ
  • @Mr.C64:该页面解释了为什么抛出 std::runtime_exception 的派生是有用的,并建议“最好抛出对象,而不是内置”,但它仍然没有解释一下扔内置插件有什么不好。
【解决方案2】:

您当前正在抛出 const char* 而不是 std::string,而是应该抛出 string("error")

编辑:错误已解决

throw string("exception ! error");

【讨论】:

  • 是的,但它的捕获:抛出(“异常!错误”);这是一个字符串
  • @Jimmy 是的,所以它没有找到捕获const char*的案例
  • @SyntacticFructose - 这是危险的(按值抛出/捕获std::string),因为必须构造一个字符串,这可能会引发错误。字符串应该被引用捕获。
【解决方案3】:
'''#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 std::runtime_error("Exception ! Error");
        }
    }

    catch(const std::exception& e)
    {
        std::cout << "Caught exception: " << e.what() << '\n';
    }
}'''

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多