How to simulate inner exception in C++

前端 未结 6 1560
逝去的感伤
逝去的感伤 2021-01-02 19:06

Basically I want to simulate .NET Exception.InnerException in C++. I want to catch exception from bottom layer and wrap it with another exception and throw again to upper la

6条回答
  •  迷失自我
    2021-01-02 19:37

    As stated by others, boost::exception is a nice option. However, like all options that use a common base class approach, they rely on all thrown exceptions being derived from that base class. If your intermediary catch handlers need to add information to an exception from a third party library it won't work.

    An option that might be sufficient is to have intermediary catch handlers like this:

    catch (std::exception& ex)
    {
       std::string msg = ex.what();
       msg.append(" - my extra info");
       ex = std::exception(msg.c_str()); // slicing assignment
       throw;                            // re-throws 'ex', preserving it's original type
    }
    

    This only works for implementations of std::exception that provide a constructor taking a string parameter (e.g. VC++). The std::exception constructor taking a string is a non-standard extension.

提交回复
热议问题