How to simulate inner exception in C++

前端 未结 6 1562
逝去的感伤
逝去的感伤 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:27

    One problem with the inner exception is the possibility to throw it again while maintaining polymorphic behaviour.

    This can be (somewhat) alleviate by actually managing the exception lifetime yourself and providing polymorphic copies.

    // Base class
    class exception: virtual public std::exception, private boost::noncopyable
    {
    public:
      virtual exception* clone() const = 0;
      virtual void rethrow() const = 0; // throw most Derived copy
    };
    
    // ExceptionPointer
    class ExceptionPointer: virtual public std::exception
    {
    public:
      typedef std::unique_ptr pointer;
    
      ExceptionPointer(): mPointer() {}
      ExceptionPointer(exception* p): mPointer(p) {}
      ExceptionPointer(pointer p): mPointer(p) {}
    
      exception* get() const { return mPointer.get(); }
      void throwInner() const { if (mPointer.get()) mPointer->rethrow(); }
    
      virtual char* what() const { return mPointer.get() ? mPointer->what() : 0; }
    
    private:
      pointer mPointer;
    };
    

    How to use ?

    try
    {
      // some code
    }
    catch(exception& e)
    {
      throw ExceptionPointer(e.clone());
    }
    
    // later on
    try
    {
    }
    catch(ExceptionPointer& e)
    {
      e.throwInner();
    }
    

提交回复
热议问题