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."は ではなく であるstd::stringためconst char*、次のようにキャッチする必要があります。

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

std::string次のようにスロー/キャッチする必要があるため、「foo」をキャッチするには:

try
{
    throw std::string("foo");
}
catch (std::string message)
{
    std::cout << message;
}
于 2014-06-12T09:20:49.860 に答える
1

polymorphsim でそれをキャッチできる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();
}
于 2014-06-12T09:29:58.140 に答える