Akash B
Akash B

Reputation: 99

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

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

Why am I getting unhandled exception error ? Even after I have added the catch block to catch thrown string messages?

Upvotes: 0

Views: 1114

Answers (2)

Kiroxas
Kiroxas

Reputation: 921

You should send an std::exception instead, like throw std::logic_error("Name cannot be numeric") you could then catch it with polymorphsim and the underlying type of your throw will no more be a problem :

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

Upvotes: 1

Iosif Murariu
Iosif Murariu

Reputation: 2054

"Name cannot be numeric." is not a std::string, it's a const char*, so you need to catch it like this:

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

To catch "foo" as std::string you need to throw/catch it like this:

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

Upvotes: 3

Related Questions