AggieDev
AggieDev

Reputation: 5045

C++ try/catch not catching exception

I have the following try/catch:

try
{
    Player newPlayer = Database::newPlayer(atoi(arguments.at(1).c_str()), arguments.at(2));
}
catch (int e)
{
    cout << "Wrong parameters used.\n";
}

My goal is to be able to add a player, and if for some reason the arguments don't match, such as putting a non-integer for arguments.at(1) or not enough arguments, but in Visual Studio if I do this then the program crashes and Visual Studio says "unhandled exception, std::out_of_range at memory location." I want my program not to crash when this happens but simply say "Wrong parameters used" as it currently is in the catch statement.

Upvotes: 0

Views: 877

Answers (3)

bcsanches
bcsanches

Reputation: 2372

You will need to catch the std::out_of_range exception, for example:

try
{
   //your throwing code
}
catch (std::out_of_range &e)
{
    cout << "Wrong parameters used.\n";
}

Also notice the catch using the reference (the & usage) instead of catching by value like you did with the int, to avoid any problem with object slicing and redundant copies.

Upvotes: 2

Pedrom
Pedrom

Reputation: 3823

You need to catch std::out_of_range instead of int

try
{
    Player newPlayer = Database::newPlayer(atoi(arguments.at(1).c_str()), arguments.at(2));
}
catch (std::out_of_range& e)
{
    cout << "Wrong parameters used.\n";
}

Upvotes: 4

AlexK
AlexK

Reputation: 1281

You need to be catching std::out_of_range not an int.

Upvotes: 7

Related Questions