jeudi 31 janvier 2019

What is benfit of throw catch over if else

I gone through this question and I know about standard exception objects. My question is, What is the benefit of using exception over simple function calling ?

For Example Code A

#include <stdexcept>

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throw std::invalid_argument( "received negative value" );
    }
}

try {
    compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
    // do stuff with exception... 
}

and Code B

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throwFunc( "received negative value" );
    }
}


compare( -1, 3 );

throwFunc(const std::string& e ) {
    // do stuff with exception... 
}

What is the benefit of Code A over Code B ? and benefit of standard exception objects ? Ultimately we just throw a variable or string.

Aucun commentaire:

Enregistrer un commentaire