Std :: logic_error instead of return false

I'm looking for someone's opinion about using std::logic_errorinstead of using a complex list of nested if / elseif return true / false.

I would like to move from many similar features like

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 this entire list of functions in one block try-catch.

Since it is derived from std::exception, I probably don’t know if this is a good idea.

Is anyone used as in the example below?

Thank you so much

AFG

+3
source share
3 answers

. ( ) , , , . , , .

, , . , ( ).

+5

.

10 ? ?

validate_data is_data_valid . true, . false, . .

+5

Since your function is called validate_data(), I would only throw an exception if there is an internal error inside the function, and use trueor falseto indicate that the function checked the input, but it was either valid( return true) or incorrect ( return false).

This will not stop you from having multiple constructs if() else if() else, but it will make the code cleaner and easier to distinguish if the data was invalid or an internal error occurred.

try {
  bool valid = validate_data(foo);
  /* process data or break if invalid */
} catch (std::exception &ex) {
  /* internal error happened */
}

as you can see, this will make your code longer, IMHO clean.

+2
source

All Articles