我想做一個簡單的自定義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永遠不會到達,並且沒有任何行被寫入控制檯。
歡迎任何想法。 謝謝!
您可能想要使用默認參數,而不是在您的異常類中重寫。 – 2012-12-21 10:59:28