Proper/elegant way of implementing C++ exception chaining?

后端 未结 4 1073
囚心锁ツ
囚心锁ツ 2021-01-04 03:34

I\'d like to implement an Exception class in C++ that mimics the one from .NET framework (and Java has something similar too), for the following purposes:

  1. E

4条回答
  •  醉话见心
    2021-01-04 04:14

    There is a lot of extra code, but the good thing is it's really EASY extra code that doesn't change at all from class to class, so it's possible to preprocessor macro it.

    #define SUB_EXCEPTION(ClassName, BaseName) \
      class ClassName : public BaseName\
      {\
      protected:\
      \
          ClassName(const ClassName& source) : BaseName(source) {};\
          ClassName& operator= (const ClassName&) {};\
      \
      public:\
      \
          ClassName(const CString &message) : BaseName(message) {};\
          ClassName(const CString &message, const BaseName &innerException) : BaseName(message, innerException) {};\
      \
          virtual CString GetExceptionName() const { return L"ClassName"; }\
      \
          virtual BaseName *Clone() const\
          {\
              ClassName *ex = new ClassName(this->Message);\
              ex->InnerException = this->InnerException ? this->InnerException->Clone() : 0;\
              return ex;\
          }\
      };
    

    Then you can define various utility exceptions by just doing:

    SUB_EXCEPTION(IoException, Exception);
    SUB_EXCEPTION(SerialPortException, IoException);
    

提交回复
热议问题