我正在尝试做一个简单的自定义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()){}
};
};
Run Code Online (Sandbox Code Playgroud)
然后我抛出错误:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我使用try/catch块
try{
checkFileExistence(fileName);
}
catch(utils::FileNotFoundException& fnfe)
{
std::cout << fnfe.what() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
运行时错误被正确抛出为FileNotFoundException,但是从未到达带有std :: cout的行,并且没有行被写入控制台.
欢迎所有想法.谢谢!
GMa*_*ckG 14
那是因为你扔了一个指针.只是做:throw FileNotFoundException(msg);.
每当你使用指针时,除非你把它放入容器/包装器中,否则你可能没有做正确的事情.