簡體   English   中英

在C ++中定義自己的異常類

[英]Defining own exception class in C++

我試圖弄清楚如何為C ++異常實現我自己的基類,這允許添加特定於錯誤的文本字符串。 我認為std :: c ++異常不可能更改錯誤文本,即使不是在C ++ 11中: http//www.cplusplus.com/reference/exception/exception/ 我還想從我的Exception-base類派生更具體的異常。 我閱讀了很多文章,但我仍然不確定我的以下實現是否涵蓋了所有重要方面。

class Exception : public std::exception {      
    public:
        Exception(const char* message) : m(message) {

        }

        virtual ~Exception() throw() {

        }

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

    protected:
        std::string m;

    private:
        Exception();
    };

這個實現很好嗎?

如果從runtime_error派生(並且您的編譯器支持繼承構造函數),則可以將類壓縮為

struct Exception : public std::runtime_error
{
  using runtime_error::runtime_error;
};

throw() :從C ++ 11開始,不推薦使用異常規范,而是使用noexcept

暫無
暫無

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

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