实现cexception c 类时,要考虑的是什么

visual What are the things to take into consideration while implementing a CException c++ class

本文关键字:是什么 cexception 类时 实现      更新时间:2023-10-16

我尝试了一个简单的C cexception实现类,从std ::异常派生。我做错了什么,我应该添加更多,我应该改进什么?C 的例外是什么?目的是使其尽可能多地独立。代码如下:编辑:

class CeException: public std::exception {
public:
    char* getascii(const wchar_t* msg)
    {
        char* pasc = new char[wcslen(msg) + 1 ];
        wcstombs(pasc, msg, wcslen(msg) + 1);
        return pasc;
    }
    CeException(const wchar_t* msg, char* pasc = NULL ):
    exception(pasc = getascii(msg))
    {
        delete[] pasc;
    }
    CeException(const string msg) 
    {   
    }
    virtual ~CeException()
    {       
    }
    BOOL GetErrorMessage(LPTSTR lpszError, UINT nMaxError, PUINT pnHelpContext = NULL )
    {
        const char* pasc = this->what();
        wchar_t* puni = new wchar_t[strlen(pasc)+1];
            mbstowcs(puni,pasc, strlen(pasc) + 1);
        wcscpy_s(lpszError,nMaxError, puni);
        delete[] puni;
        return 0;
    }
    void Delete()
    {
        delete this;
    }

};

我使用您的指示进行了最终实现的编辑。

通常您不需要在异常类中实现方法,因此看起来像这样:

class YourException : public std::runtime_error
{
public:
    explicit YourException(const std::string & msg) :
        std::runtime_error(msg)
    {
    }
};

我不明白有其他方法的原因。

您不应该从其构造函数中抛出异常。相反,客户端代码应引发您的异常:

    throw YourException("Some error");