我的构造函数中有以下代码块(这只是一个示例,问题不是关于拆分,而是抛出一个通用异常.另外,不能使用Boost库.
Transfer::Transfer(const string &dest){ try{ struct stat st; char * token; std::string path(PATH_SEPARATOR) // if it is \ or / this macro will solve it token = strtok((char*)dest.c_str(),PATH_SEPARATOR) // while(token != NULL){ path += token; if(stat(path.c_str(),&st) != 0){ if(mkdir(path.c_str()) != 0){ std:string msg("Error creating the directory\n"); throw exception // here is where this question lies } } token = strtok(NULL,PATH_SEPARATOR); path += PATH_SEPARATOR; } }catch(std::exception &e){ //catch an exception which kills the program // the program shall not continue working. } }
我想要的是如果目录不存在而无法创建,则抛出异常.我想抛出一个通用异常,我怎么能用C做呢?
PS:dest具有以下格式:
dest = /usr/var/temp/current/tree
解决方法
请检查
this answer.这解释了如何使用您自己的异常类
class myException: public std::runtime_error { public: myException(std::string const& msg): std::runtime_error(msg) {} }; void Transfer(){ try{ throw myException("Error creating the directory\n"); }catch(std::exception &e){ cout << "Exception " << e.what() << endl; //catch an exception which kills the program // the program shall not continue working. } }
此外,如果您不想要自己的课程,您可以简单地执行此操作
throw std::runtime_error("Error creating the directory\n");