Reputation: 33
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
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
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
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