Friday 15 March 2013

c++ - How to make exception code DRY? -



c++ - How to make exception code DRY? -

this question has reply here:

code reuse in exception handling 6 answers

i trying debug application using exception catch-rethrows. exception handling code longer of blocks debugging, , it's copy-pasted.

is there improve way repeatedly express below code? suspect macros way go here, avoid macros plague.

seek { // code here... } grab (std::exception & e) { errormsglog::log("error", "std exception caught in " __func__ " " __file__ " " __line__, e.what()); throw e; } grab (exception & e) { errormsglog::log("error", "builder exception caught in " __func__ " " __file__ " " __line__, e.message); throw e; } grab (...) { errormsglog::log("error", "unknown exception caught in " __func__ " " __file__ " " __line__); throw std::runtime_error ("unknown exception in " __func__ " " __file__ " " __line__); }

the best way implement using macros. macro definition little bit ugly, calling macro pretty easy, , not need re-organize code. here sample shows how implement it:

class="lang-cpp prettyprint-override">#define run_safe(code) seek {\ code\ }\ grab (std::exception & e)\ {\ errormsglog::log("error");\ throw e;\ }\ grab (exception & e)\ {\ errormsglog::log("error");\ throw e;\ }\ grab (...)\ {\ errormsglog::log("error");\ throw std::exception();\ }\ int main(){ run_safe( cout << "hello world\n"; ) }

if adamant not using macros, utilize approach suggested @juanchopanza , utilize higher-order function check takes code parameter. approach require refactor code bit though. here how implement it:

class="lang-cpp prettyprint-override">void helloworld(){ cout << "hello world\n"; } void runsafe(void (*func)()){ seek { func(); } grab (std::exception & e) { errormsglog::log("error"); throw e; } grab (exception & e) { errormsglog::log("error"); throw e; } grab (...) { errormsglog::log("error"); throw std::exception(); } } int main(){ runsafe(helloworld); }

c++ exception dry c++03

No comments:

Post a Comment