string - C++ Throwing same error message from different places in code -
i want throw same error different places. here's example:
int devide(int a,int b) { if(b==0) { throw "b must different 0"; } return 0; } int mod(int a,int b) { if(b==0) { throw "b must different 0"; } return 0; }
and in main function:
int main() { try { devide(1,0); } catch(char const* e) { cout << e << endl; } try { mod(1,0); } catch(char const* e) { cout << e << endl; } return 0; }
now output of program is:
b must different 0 b must different 0
as can see, error nature same, error message different. what's best practice can follow in case, scalable? let's have 100 different types of exceptions, when throw exception devisor different 0
want same messege everywhere exception thrown.
edit: thinking 2 options:
- for every exception may throw define own class inherit
std::exception
. every exception can put inexceptions.cpp
. i can define 1 one
class myexception
inheritstd::exception
, in constructor request error string. , can somewhere(i still can't think of put them) define static string constants describe message. instance, if have definemyexception
can use this:int devide(int a,int b) { if(b==0) { throw new myexception(myexception::devision_by_zero); } }
where myexception::devision_by_zero
string constant.
i think second approach requires less coding doesn't seem pretty me.
so there better aproach 2 above?
the best can create own exception , throw that.
class exception : public std::exception { public: template< typename... args > exception( const std::string& msg, args... args ); virtual ~exception() throw (); //! overrides std::exception virtual const char* what() const throw(); private: //! log message_ void log() const; protected: std::string message_; }; template< typename... args > exception::exception( const std::string& msg, args... args ) : message_( strfmt::format( msg, args ... ) ) { log(); } class myexception : public exception { myexception() : exception( std::string("b must different 0") ) }
if further plan exit program on uncaught exceptions, possible install termination handler, rethrow exception.
static void terminate() { static bool tried_rethrow = false; try { if ( !tried_rethrow ) { tried_rethrow = true; throw; } } catch ( const std::runtime_error& err ) { std::cout << err.what(); } catch ( const exception& err ) { std::cout << err.what(); } catch ( ... ) { } }
and in main.cpp:
std::set_terminate( terminate );
that way possible handle uncaught exceptions @ single place.
Comments
Post a Comment