未处理的异常,甚至在添加try-catch块之后?c++

Unhandled exception, even after adding try-catch block ? C++

本文关键字:try-catch 之后 c++ 添加 异常 未处理      更新时间:2023-10-16
try
{
    bool numericname=false;
    std::cout <<"nnEnter 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 <<"nn";
}

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

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

您应该发送std::exception,如throw std::logic_error("Name cannot be numeric")然后你可以用多态捕获它,你的投掷的潜在类型将不再是一个问题:

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();
}