2013-10-31 44 views
-2

我曾嘗試:投擲,錯誤消息C++

class MyException : public std::runtime_error {}; 

throw MyException("Sorry out of bounds, should be between 0 and "+limit); 

我不知道我怎麼能實現這樣的功能。

+0

花費時間,從谷歌的點擊可能會超過來到這裏,被濫用不問實際問題還清。 [推薦C++書籍列表](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?rq=1)也有一些關於這類東西的傑出部分。 – WhozCraig

回答

0

這裏有兩個問題:如何讓你的異常接受字符串參數,以及如何創建自運行信息的字符串。

class MyException : public std::runtime_error 
{ 
    MyExcetion(const std::string& message) // pass by const reference, to avoid unnecessary copying 
    : std::runtime_error(message) 
    {}   
}; 

然後你有不同的方式來構造字符串參數:

  1. std::to_string是最方便的,但它是一個C++ 11功能。

    throw MyException(std::string("Out of bounds, should be between 0 and ") 
            + std::to_string(limit)); 
    
  2. 或者使用boost::lexical_cast(函數名稱的鏈接)。

    throw MyException(std::string("Out of bounds, should be between 0 and ") 
            + boost::lexical_cast<std::string>(limit)); 
    
  3. 您還可以創建一個C字符串緩衝區並使用a printf style commandstd::snprintf將是首選,但也是C++ 11。在* *成千上萬的「C++自定義異常對象」

    char buffer[24]; 
    int retval = std::sprintf(buffer, "%d", limit); // not preferred 
    // could check that retval is positive 
    throw MyException(std::string("Out of bounds, should be between 0 and ") 
            + buffer); 
    
+0

如果limit是一個int,std :: string(limit)會工作嗎? –

+0

約翰史密斯,謝謝。我爲未來的讀者編輯和更正。 – NicholasM

0

您需要爲接受一個字符串的MyException定義一個構造函數,然後將其發送到std :: runtime_error的構造函數。事情是這樣的:

class MyException : public std::runtime_error { 
public: 
    MyException(std::string str) : std::runtime_error(str) 
    { 
    } 
};