我有这两个函数,有重复的异常处理,其唯一目的是显示错误消息:
void func1() noexcept {
  try {
    do_task();
    do_another_task();
  } catch (const std::out_of_range& e) {
    show_msg("Out of range error", e.what());
  } catch (const std::logic_error& e) {
    show_msg("Logic error", e.what());
  } catch (const std::system_error& e) {
    show_msg("System error", e.what());
  } catch (const std::runtime_error& e) {
    show_msg("Runtime error", e.what());
  } catch (const std::exception& e) {
    show_msg("Generic error", e.what());
  }
}
void func2() noexcept {
  try {
    do_something();
    do_something_else();
    do_even_more();
  } catch (const std::out_of_range& e) {
    show_msg("Out of range error", e.what());
  } catch (const std::logic_error& e) {
    show_msg("Logic error", e.what());
  } catch (const std::system_error& e) {
    show_msg("System error", e.what());
  } catch (const std::runtime_error& e) {
    show_msg("Runtime error", e.what());
  } catch (const std::exception& e) {
    show_msg("Generic error", e.what());
  }
}
我可以处理 std::exception 并显示一个通用消息,但我想更具体,这就是为什么我抓住所有可能的异常。
我想重用这个异常处理代码。我想到了这个:
void run_treated(std::function<void()> func) noexcept {
  try {
    func();
  } catch // ... all the catches go here
}
void func1() noexcept {
  run_treated([]()->void {
    do_task();
    do_another_task();
  });
}
void func2() noexcept {
  do_something();
  do_something_else();
  do_even_more();
}
- 这是一个好方法吗?
- 如果是这样, run_treated将被召唤 很多。我应该关注表现吗?
- 还有其他方法吗?