【问题标题】:Unhandled exception, even after adding try-catch block ? C++未处理的异常,即使在添加 try-catch 块之后? C++
【发布时间】:2014-06-12 09:16:08
【问题描述】:
try
{
    bool numericname=false;
    std::cout <<"\n\nEnter the Name of Customer: ";
    std::getline(cin,Name);
    std::cout<<"\nEnter the Number of Customer: ";
    std::cin>>Number;
    std::string::iterator i=Name.begin();
    while(i!=Name.end())
    {
        if(isdigit(*i))
        {
            numericname=true;
        }
        i++;
    }
    if(numericname)
    {
        throw "Name cannot be numeric.";
    }
} catch(string message)
{
    cout<<"\nError Found: "<< message <<"\n\n";
}

为什么我收到未处理的异常错误?即使在我添加了 catch 块来捕获抛出的字符串消息之后?

【问题讨论】:

  • 试试catch (char* msg)catch (const char* msg)之类的东西
  • (char* message) 工作! :D 但是之前的代码有什么问题?我确实添加了#include
  • 非常感谢,它成功了!!
  • 查看std::string的答案

标签: c++ exception try-catch unhandled


【解决方案1】:

"Name cannot be numeric." 不是std::string,而是const char*,所以你需要像这样捕捉它:

try
{
    throw "foo";
}
catch (const char* message)
{
    std::cout << message;
}

要将“foo”捕获为std::string,您需要像这样抛出/捕获它:

try
{
    throw std::string("foo");
}
catch (std::string message)
{
    std::cout << message;
}

【讨论】:

    【解决方案2】:

    您应该发送std::exception,例如throw std::logic_error("Name cannot be numeric") 然后你可以用 polymorphsim 捕捉它,你的 throw 的底层类型将不再是一个问题:

    try
    {
        throw std::logic_error("Name cannot be numeric"); 
        // this can later be any type derived from std::exception
    }
    catch (std::exception& message)
    {
        std::cout << message.what();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 2018-12-13
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多