是否可以编写一个“捕获”多个不同异常的异常类型?

时间:2013-04-30 14:17:46

标签: c++ exception-handling multiple-inheritance virtual-inheritance

我想知道是否有可能(通过巧妙的转换规则)编写一个有助于以下内容的“异常”类:

而不是写作:

try {
 ...
} catch (std::execption const e) {    // StdLib exceptions
} catch (CException* pEx) {           // MFC exceptions
} catch (CORBA::Exception const& e) { // CORBA exceptions
} // note handling code inside catch blocks omitted for brevity

如果可以构造一个类似的类型,那将是很好的:

try {
  ...
} catch( magic_exception_handle const& e) { // catches all three types mentioned above
  const std::string msg = e.what(); // could also provide generalized message extraction
}

这可能吗?怎么样?

注意:我不喜欢的其他解决方案:

  • 我可以catch(...),但我想要抓住所有。
  • catch-handler函数:

    void handler3() {
      try {
        throw;
      } catch (std::execption const e) {    // StdLib exceptions
      } catch (CException* pEx) {           // MFC exceptions
      } catch (CORBA::Exception const& e) { // CORBA exceptions
      } // note handling code inside catch blocks omitted for brevity
    }
    
    ...
    try { ... } catch(...) { handler3(); }
    

    也没有删除它,因为当向外抛出任何其他异常时,它首先会捕获任何其他异常,导致在重新抛出之前过早的堆栈展开。 (这对Windows上任何导致的崩溃转储非常不方便。)

  • 我可以为catch块写一个宏。 (

那么,是否可以创建magic_exception_handle类型?它已经完成了吗?

1 个答案:

答案 0 :(得分:1)

唯一真正的选择是颠倒逻辑:

template<typename F, typename... Args>
auto convert_exceptions(F &&f, Args... &&args)
-> decltype(f(std::forward<Args>(args)...)) {
   try {
      return f(std::forward<Args>(args)...));
   } catch (std::exception const e) {    // StdLib exceptions
      std::throw_with_nested(magic_exception{...});
   } catch (CException* pEx) {           // MFC exceptions
      std::throw_with_nested(magic_exception{...});
   } catch (CORBA::Exception const& e) { // CORBA exceptions
      std::throw_with_nested(magic_exception{...});
   }
}

您现在可以写:

try {
   convert_exceptions([&]() {
      // ...
   });
} catch (const magic_exception &e) {
   // ...
}
相关问题