未处理的异常,即使在添加try-catch块之后? C ++

时间:2014-06-12 09:16:09

标签: c++ exception try-catch unhandled

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块以捕获抛出的字符串消息之后呢?

2 个答案:

答案 0 :(得分:3)

"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;
}

答案 1 :(得分:1)

您应该发送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();
}