makanbeling
makanbeling

Reputation: 33

can't catch an exception from a function in c++

Like the title said, I can't catch an exception thrown by a function. It just says "terminate called after throwin an instance of tocccli::InvalidParametersError*"

try{
  cmd_parameters = parse_cmd(argc, argv);
}
catch (InvalidParametersError e){
  // blablabla
}

The function that throws the exception

std::vector<CmdParam> parse_cmd(int argc, char* argv[]){
for (int i = 1; i < argc; ++i)
{
  if (argv[i][0] == '-')
  {
   //blablala
  }
  else
  {
    if (result.empty())
    {
      throw new InvalidParametersError(
          "First parameter have to be an option (e.g. starts with a dash)");
    }

    result.back().arguments.push_back(argv[i]);
  }
}

return result;
}

the function is inside a namespace called tocccli Am I missing something?

Upvotes: 3

Views: 232

Answers (3)

Mansour
Mansour

Reputation: 1

just add ampersand in front of the error you want to catch, in the catch block and done.

catch (InvalidParametersError &e)

Upvotes: -2

tinkertime
tinkertime

Reputation: 3042

You are throwing a pointer to an InvalidParametersError, and catching by value. Consider changing your throw to:

throw InvalidParametersError("First parameter have to be an option (e.g. starts with a dash)");

And as pointed out by @pmr, also consider catching by const ref

try {
    cmd_parameters = parse_cmd(argc, argv);
} catch (const InvalidParametersError &e) {
    // ....
}

Upvotes: 3

pzed
pzed

Reputation: 837

Don't throw with the new keyword in parse_cmd():

std::vector<CmdParam> parse_cmd(int argc, char* argv[]){
for (int i = 1; i < argc; ++i)
{
  if (argv[i][0] == '-')
  {
   //blablala
  }
  else
  {
    if (result.empty())
    {
      throw InvalidParametersError(  // <-- No new keyword here
          "First parameter have to be an option (e.g. starts with a dash)");
    }

    result.back().arguments.push_back(argv[i]);
  }
}

return result;
}

Catch by const reference:

try{
  cmd_parameters = parse_cmd(argc, argv);
}
catch (const InvalidParametersError& e){
  // blablabla
}

Upvotes: 4

Related Questions