Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

exception

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?

like image 687
makanbeling Avatar asked May 25 '26 17:05

makanbeling


2 Answers

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
}
like image 104
pzed Avatar answered May 28 '26 06:05

pzed


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) {
    // ....
}
like image 40
tinkertime Avatar answered May 28 '26 05:05

tinkertime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!