是一个宏来捕捉不同地方的一组例外罚款吗?

Mic*_*ann 6 c++ macros exception try-catch

我有一组函数,需要将可能抛出的异常转换为错误代码.

为此,我用try/catch语句包装了实际的调用:

int f_with_error_codes()
{
  try {
    f(); // wrapped function call

    return E_SUCCESS;
  }
  catch (error1&) {
    return E_ERROR1;
  }
  catch (error2&) {
    return E_ERROR2;
  }
}

int g_with_error_codes(int a);
{
  try {
    G g(a);        // wrapped expressions
    g.print();

    return E_SUCCESS;
  }
  catch (error1&) {
    return E_ERROR1;
  }
  catch (error2&) {
    return E_ERROR2;
  }
}

...
Run Code Online (Sandbox Code Playgroud)

这些捕获规模重演.此外,每当添加新的异常时,都必须将新的catch子句添加到每个调用包装器中.

下面的宏是否适合替换catch语句?

#define CATCH_ALL_EXCEPTIONS  \
catch (error1&) {             \
  return E_ERROR1;            \
}                             \
catch (error2&) {             \
  return E_ERROR2;            \
}
Run Code Online (Sandbox Code Playgroud)

哪会导致:

int f_with_error_codes()
{
  try {
    f(); // the wrapped

    return E_SUCCESS;
  }
  CATCH_ALL_EXCEPTIONS
Run Code Online (Sandbox Code Playgroud)

Hen*_*rik 10

您可以使用函数而不是像这样的宏:

int f_with_error_codes() 
{ 
  try { 
    f(); // wrapped function call 

    return E_SUCCESS; 
  } 
  catch (...) { 
    return error_code();
  } 
}

int error_code()
{
  try { 
    throw;
  } 
  catch (error1&) { 
    return E_ERROR1; 
  } 
  catch (error2&) { 
    return E_ERROR2; 
  } 
}
Run Code Online (Sandbox Code Playgroud)


iam*_*ind 7

对于您的情况,您不需要任何宏.
只需一个包含virtual函数的简单基类就足够了.

class error : public std::exception { // std::exception is your wish
  const char* what () throw(); // needed if std::exception is based
  virtual int GetValue () const = 0;  // <--- This is the core part
}
Run Code Online (Sandbox Code Playgroud)

现在,继承所有error#类的这个类:

class error1 : public error {
  virtual int GetValue () const { return E_ERROR1; } // <--- override
};
// ...
Run Code Online (Sandbox Code Playgroud)

最后你的代码就像这样简单:

void f_with_error_codes()
{
  try {
    f(); // wrapped function call
    return E_SUCCESS;
  }
  catch (error& e) {  // <--- base handle
    return e.GetValue();
  }
}
Run Code Online (Sandbox Code Playgroud)

不要virtual在这里担心功能成本.因为它是最小的,也是罕见事件的例外; 非常小的成本virtual对于使代码可维护和扩展是值得的.