How to make DRY exception code?

I am trying to debug my application using catch-rethrows exceptions. My exception handling code is longer than some of the blocks I am debugging, and all this has been copied.

Is there a better way to re-express the code below? I suspect macros are the way to go, but I usually avoid macros like the plague.

try { // Code here... } catch (std::exception & e) { ErrorMsgLog::Log("Error", "std exception caught in " __func__ " " __FILE__ " " __LINE__, e.what()); throw e; } catch (Exception & e) { ErrorMsgLog::Log("Error", "Builder exception caught in " __func__ " " __FILE__ " " __LINE__, e.Message); throw e; } catch (...) { ErrorMsgLog::Log("Error", "Unknown exception caught in " __func__ " " __FILE__ " " __LINE__); throw std::runtime_error ("Unknown Exception in " __func__ " " __FILE__ " " __LINE__); } 
+6
source share
1 answer

The best way to implement this is probably with macros. Defining a macro is a little ugly, but calling a macro will be pretty simple, and you won’t need to re-arrange the code. Here is an example that shows how you could implement it:

 #define RUN_SAFE(code) try {\ code\ }\ catch (std::exception & e)\ {\ ErrorMsgLog::Log("Error");\ throw e;\ }\ catch (Exception & e)\ {\ ErrorMsgLog::Log("Error");\ throw e;\ }\ catch (...)\ {\ ErrorMsgLog::Log("Error");\ throw std::exception();\ }\ int main(){ RUN_SAFE( cout << "Hello World\n"; ) } 

If you are really not sure that you are not using macros, you can use the approach suggested by @juanchopanza and use a higher order function for checking, which takes the code as a parameter. This approach will probably require you to reorganize your code a bit. Here's how you could implement it:

 void helloWorld(){ cout << "Hello World\n"; } void runSafe(void (*func)()){ try { func(); } catch (std::exception & e) { ErrorMsgLog::Log("Error"); throw e; } catch (Exception & e) { ErrorMsgLog::Log("Error"); throw e; } catch (...) { ErrorMsgLog::Log("Error"); throw std::exception(); } } int main(){ runSafe(helloWorld); } 
0
source

Source: https://habr.com/ru/post/976883/


All Articles