如何使异常代码DRY



我正试图通过使用异常捕获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__);
  }

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

#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 Worldn";
  )
}

如果你真的坚持不使用宏,你可以使用@juancpanza建议的方法,并使用一个高阶函数进行检查,将代码作为参数。不过,这种方法可能需要对代码进行一些重构。以下是如何实现它:

void helloWorld(){
  cout << "Hello Worldn";
}
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);
}

最新更新