I am looking for someones opinion about the usage of std::logic_error instead of using a complicated list of nested if/elseif return true/false.
I would like to move from a lot of similar function like the one below
bool validate_data(){
std::vector<int> v;
//fill with data
if( v.find(10) == v.end() ){
return false;
}
// other checks that return false
}
to
bool validate_data(){
std::vector<int> v;
//fill with data
if( v.find(10) == v.end() ){
throw std::logic_error("error message");
}
// other checks that return false
}
and call all this list of functions in a single try-catch block.
Since it is a derived from std::exception probably I don’t know if it is a good idea.
Is anyone using like the example below?
Thanks a lot
AFG
You should only use exceptions for exceptional circumstances. Using (and checking) return values is far more efficient when the chances of it being true or false are non-trivial. Exceptions are more efficient only when the chance of throwing is so small as to out-weigh the cost of the return-value check.
So if the chances of invalid data are very very low, then go with exceptions. Otherwise, the current solution should not only be fine, but slightly more efficient as well (As throwing and handling is relatively expensive).