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

4

2 回答 2

3

"Name cannot be numeric."不是 a std::string,而是 a 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;
}
于 2014-06-12T09:20:49.860 回答
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();
}
于 2014-06-12T09:29:58.140 回答