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?
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
}
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) {
// ....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With