簡體   English   中英

C ++重載異常的構造函數

[英]C++ overloading constructor of exceptions

我試圖做出自己的例外,即可以使用一個或兩個參數拋出該異常。 所以我要做的就是重載異常的構造函數。 但是似乎沒有調用第二個構造函數。 這是我的代碼:

代碼上市-1。

class myException: public std::exception {
public:
    /*
     * first constructor
     */
    myException(unsigned short ExceptionCode):exception(){
        code = ExceptionCode;
        errorMessage = std::string("");
    }
    /*
     * second constructor
     */
    myException(unsigned short ExceptionCode, std::string errorMessage):exception(){
        std::cout << "debugging message";//present here for debugging purpose only
        code = ExceptionCode;
        this->errorMessage = errorMessage;
    }

    const char * what() const throw ()
    {   
        std::string tmp;
        switch(code){
            case MYERROR_CODE_1:
                tmp = std::string("MYERROR_CODE_1 : ");
                if(errorMessage.empty())
                    tmp += std::string("this is a default error message for code 1");
                tmp += errorMessage;
                break;
            case MYERROR_CODE_2:
                tmp = std::string("MYERROR_CODE_2 : ");
                if(errorMessage.empty())
                    tmp += std::string("this is a default error message for code 2");
                tmp += errorMessage;
        }


      return tmp.c_str();
    }
    ~myException() throw(){}

private:
    std::string errorMessage;
    unsigned short   code;
};

例如,當我這樣稱呼它時:

代碼上市-2。

void myFunction(myClass myObject){
    //some code
    if(conditionsMeet)
         throw myException(MYERROR_CODE_2,"this is a more specific custom message for code 2");
    //some other code
}

“調試消息”根本沒有出現。 當我評論“第一個構造函數”時,我得到一個錯誤和很多警告。

錯誤上市-1。

main.cpp:28:41: error: no matching function for call to 'myException::myException(ExceptionCode)'
     throw myException(MYERROR_CODE_2);
                                         ^
main.cpp:28:41: note: candidates are:
In file included from Node.h:12:0,
                 from main.cpp:10:
myException.h:50:5: note: myException::myException(short unsigned int, std::string)
     myException(unsigned short ExceptionCode, std::string errorMessage):exception(){
     ^
myException.h:50:5: note:   candidate expects 2 arguments, 1 provided
myException.h:44:7: note: myException::myException(const myException&)
 class myException: public std::exception {
       ^
myException.h:44:7: note:   no known conversion for argument 1 from 'ExceptionCode' to 'const myException&'

編輯:錯誤代碼定義如下:

代碼上市-2。

enum ExceptionCode{
    MYERROR_CODE_1                 = 1,
    MYERROR_CODE_2                 = 2,
};

誰能向我解釋我做錯了什么,為什么? 提前致謝。

正如Massa所指出的,由於示例行而不會引發您得到的編譯錯誤:

throw myException(MYERROR_CODE_2,"this is a more specific custom message for code 2");

而是因為您在代碼的其他位置調用了第一個構造函數,例如:

throw myException(MYERROR_CODE_2);

正如其他人已經回答的那樣,該錯誤是其他地方的錯誤。 我可以編譯並運行您的程序,而不會出現您提到的問題。 但是,您的代碼中還有其他問題。 您正在用what方法創建一個臨時string ,並返回該字符串保存的字符數組 這是未定義的行為,因為從該方法返回后,該string不存在,並且指針指向無效的內存。

您有一個枚舉類型ExceptionCode MYERROR_CODE_2的類型為ExceptionCode ,不是unsigned short 您還具有也稱為ExceptionCode的變量。 這是一個壞主意。 不要那樣做

順便說一句,我建議您擺脫錯誤代碼,並為每個錯誤代碼派生一個子類,這與從std :: exception派生出幾種類型的方法幾乎相同。

以您的示例為例,並提供錯誤代碼的定義,然后全部編譯。

但是,what()函數中存在嚴重的錯誤,有一天會導致崩潰。

您正在臨時調用c_str(),然后將指針返回到現在已釋放的內存。 這非常非常糟糕。

您需要將字符串存儲在異常中,並在構造函數期間進行構建以確保安全。

提供的示例:

#include <iostream>
#include <exception>

enum Errors {
    MYERROR_CODE_1,
    MYERROR_CODE_2
};


class myException: public std::exception {
public:
    /*
     * only one constructor necessary
     */
    myException(unsigned short ExceptionCode, std::string errorMessage = std::string())
    : exception()
    , message(buildErrorMessage(ExceptionCode, errorMessage))
    , code(ExceptionCode)
    {
        std::cout << "debugging message\n";//present here for debugging purpose only
    }

    static std::string buildErrorMessage(unsigned short code, const std::string& errorMessage) {
        std::string tmp;
        switch(code){
            case MYERROR_CODE_1:
                tmp = std::string("MYERROR_CODE_1 : ");
                if(errorMessage.empty())
                    tmp += std::string("this is a default error message for code 1");
                tmp += errorMessage;
                break;
            case MYERROR_CODE_2:
                tmp = std::string("MYERROR_CODE_2 : ");
                if(errorMessage.empty())
                    tmp += std::string("this is a default error message for code 2");
                tmp += errorMessage;
        }
        return tmp;
    }

    const char * what() const throw ()
    {   
        return message.c_str();
    }

private:
    std::string message;
    unsigned short   code;
};

using namespace std;

int main()
{
    int err = MYERROR_CODE_1;

    try {
        throw myException(err);
    }
    catch(exception& e) {
        cout << e.what() << endl;
    }

    try 
    {
        throw myException(err, "more info");
    }
    catch(exception& e) {
        cout << e.what() << endl;
    }


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM