如何提取C ++中的重复尝试捕获模式 [英] How can I abstract out a repeating try catch pattern in C++

查看:79
本文介绍了如何提取C ++中的重复尝试捕获模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重复执行几个成员函数的模式,如下所示:

I have a pattern that repeats for several member functions that looks like this:

int myClass::abstract_one(int sig1)
{
  try {
    return _original->abstract_one(sig1);
  } catch (std::exception& err) {
    handleException(err);
  } catch (...) {
    handleException();
  }
}

bool myClass::abstract_two(int sig2)
{
  try {
    return _original->abstract_two(sig2);
  } catch (std::exception& err) {
    handleException(err);
  } catch (...) {
    handleException();
  }
}

[...]

int myClass::abstract_n(bool sig3a, short sig3b)
{
  try {
    return _original->abstract_n(sig3a, sig3b);
  } catch (std::exception& err) {
    handleException(err);
  } catch (...) {
    handleException();
  }
}

其中第一个到第n个是纯虚拟方法 myClass _original 是具体实现的抽象接口。

Where abstract one through n are methods of a pure virtual abstract interface for which myClass and _original are concrete implementations.

我不希望这种模式在代码中重复出现,并且想找到一种方法来消除重复的 try / catch 模式和代码是一个抽象,但是我想不出没有宏在C ++中做到这一点的好方法。我认为可以使用模板来更好地做到这一点。

I don't like that this pattern repeats in the code and would like to find a way to eliminate the repeating try / catch pattern and code as a single abstraction, but I can't think of a good way to do this in C++ without macros. I would think that there is a way with templates to do this better.

请提出一种干净的方法来重构此代码,以抽象出重复的模式。

Please suggest a clean way to refactor this code to abstract out the repeated pattern.

推荐答案

我问了一个非常相似的概念性问题,请参见

I asked a very similar conceptual question, see Is re-throwing an exception legal in a nested 'try'?.

基本上,可以通过捕获所有异常,调用该处理程序并重新抛出活动的异常,将各种异常处理程序移至单独的函数。

Basically, you can move the various exception handlers to a separate function by catching all exceptions, calling the handler and rethrowing the active exception.

void handle() {
 try {
  throw;
 } catch (std::exception& err) {
   handleException(err);
 } catch (MyException& err) {
   handleMyException(err);
 } catch (...) {
   handleException();
 }
}

try {
   return _original->abstract_two(sig2);
} catch (...) {
   handle();
}

它的伸缩性很好,可以使用更多不同的异常类型来区分。如果愿意,可以将第一个 try .. catch(...)打包到宏中:

It scales well with more different exception kinds to differenciate. You can pack the first try .. catch(...) into macros if you like to:

BEGIN_CATCH_HANDLER
return _original->abstract_two(sig2);
END_CATCH_HANDLER

这篇关于如何提取C ++中的重复尝试捕获模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆