如何制作异常代码DRY?

Que*_*onC 6 c++ exception dry c++03

我试图通过使用异常catch-rethrows来调试我的应用程序.我的异常处理代码比我正在调试的一些块长,并且它都是复制粘贴的.

有没有更好的方法来反复表达以下代码?我怀疑宏是这里的方式,但我通常会避免像瘟疫这样的宏.

  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__);
  }
Run Code Online (Sandbox Code Playgroud)

zac*_*ckg 0

实现这一点的最佳方法可能是使用宏。宏定义有点难看,但是调用宏将非常容易,并且您不需要重新组织代码。下面是一个示例,展示了如何实现它:

#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";
  )
}
Run Code Online (Sandbox Code Playgroud)

如果您确实坚决不使用宏,则可以使用@juanchopanza建议的方法,并使用高阶函数进行以代码作为参数的检查。不过,这种方法可能需要您稍微重构一下代码。以下是实现它的方法:

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);
}
Run Code Online (Sandbox Code Playgroud)