2010-09-10 64 views
6

我想做一個簡單的自定義runtime_error。我定義類:如何做我自己的自定義運行時錯誤類?

#include <string> 
#include <stdexcept> 


namespace utils{ 

class FileNotFoundException: public std::runtime_error{ 
    public: 
    FileNotFoundException():runtime_error("File not found"){} 
    FileNotFoundException(std::string msg):runtime_error(msg.c_str()){} 
}; 

}; 

然後我拋出錯誤:

bool checkFileExistence(std::string fileName) 
{ 
    boost::filesystem::path full_path = boost::filesystem::system_complete(boost::filesystem::path(fileName)); 
    if (!boost::filesystem::exists(full_path)) 
    { 
    char msg[500]; 
    _snprintf(msg,500,"File %s doesn't exist",fileName.c_str()); 
    throw new FileNotFoundException(msg); 
    } 
} 

我使用try/catch塊

try{ 
      checkFileExistence(fileName); 
    } 
    catch(utils::FileNotFoundException& fnfe) 
     { 
      std::cout << fnfe.what() << std::endl; 
    } 

運行時錯誤被正確地拋出FileNotFoundException異常而行std :: cout永遠不會到達,並且沒有任何行被寫入控制檯。

歡迎任何想法。 謝謝!

+0

您可能想要使用默認參數,而不是在您的異常類中重寫。 – 2012-12-21 10:59:28

回答

13

這是因爲你扔了一個指針。只要:throw FileNotFoundException(msg);

每當你使用一個指針時,除非你把它放到一個容器/包裝器中,否則你可能沒有做正確的事情。

5

你寫throw new FileNotFoundException(msg),應該是'拋出FileNotFoundException(msg)'。規則是按價值拋售,按參考收穫。

+1

除非你是使用MFC的微軟,那麼規則是通過指針拋出並通過指針捕獲。他們在全面支持標準拋出/捕獲之前創建了他們的異常類,這導致了一些有趣的妥協。 – 2010-09-10 21:13:08

3

實際上,您正在拋出一個指向堆分配對象(FileNotFoundException *)的指針,因此類型不匹配。一般情況下,按價值計算並參考(rule 73)。

1

順便說一句,用以下聲明創建msg字符串的副本。

FileNotFoundException(std::string msg):runtime_error(msg.c_str()){} 

改爲寫上「const std :: string & msg」。它會在堆棧上放一個參考。現在你把整個字符串放在一個堆棧上。

+0

更正!感謝您的想法! – Killrazor 2013-04-11 15:46:44

相關問題