如何避免在catch块中写入重复的代码?

Eng*_*ain 6 c++ optimization exception-handling try-catch throw

我正在使用QT 4.8(C++)进行桌面应用程序项目,并编写异常处理,如下所示:

void callerMethod()
{
  try
  {
   method1();
  }
  catch(Exception1& e)
  {
    // display critcal error message
    // abort application
  }
  catch(std::Exception& e)
  {
   // print exception error message
  }
  catch(...)
  {
   // print unknown exception message
  } 
}

void method1()
{
  try
  {
   // some initializations
   // some operations (here exceptions can occur)
   // clean-up code (for successful operation i.e no exception occurred)
  }
  catch(Exception1& e)
  {
   // clean-up code
   throw e;
  }
  catch(Exception2& e)
  {
   // clean-up code
   throw e;
  }
  catch(Exception3& e)
  {
   // clean-up code
   throw e;
  }
  catch(...)
  {
   // clean-up code
   throw;
  }
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是我需要在每个catch块中编写清理代码吗?有什么方法可以避免重复编写代码吗?

NOTE :: [ 在method1() ]我想重新抛出我的调用者发生的异常.所以我无法在单个catch块中捕获它们,因为那时类型信息将丢失.

thi*_*ton 8

Method1可以通过两个概念大大简化:

  1. RAII.将任何清理代码放入析构函数中,清理代码将集中.
  2. 使用不合格的throw,您不需要知道抛出的异常类型.

所以,method1()应该看起来像:

void method1()
{
     // some initializations of RAII objects
     // some operations (here exceptions can occur)
}
Run Code Online (Sandbox Code Playgroud)

如果从中派生Exception1 catch,callerMethod则可以删除第一个子句std::exception,因为该what()方法是虚拟的.