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); }
zackg source share