【发布时间】:2010-09-10 21:06:26
【问题描述】:
我正在尝试做一个简单的自定义 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 的行,并且没有将任何行写入控制台。
欢迎所有想法。 谢谢!
【问题讨论】:
-
您可能希望使用默认参数而不是在您的异常类中覆盖。