c++ - Can I make a #define and use it in a throw? -
can make this?
#define n_valid "is not valid id" ... throw n_valid; ... catch(char *message){ fprintf(stderr,"%s",message);}
yes, except throwing const char *
, not char *
: https://ideone.com/usnitg
#include <iostream> using std::cout; using std::endl; #define n_valid "is not valid id" void function_throws() { throw n_valid; } int main() { try { function_throws(); } catch(const char *message) // <= note const here! { cout << message << endl; } }
however, joel correct should avoid doing this. if want use macro here, try using argument std::exception object: https://ideone.com/dsx1rf
void function_throws() { throw invalid_argument(n_valid); } int main() { try { function_throws(); } catch(const invalid_argument& ex) { cout << "invalid_argument: " << ex.what() << endl; } }
Comments
Post a Comment