我的构造函数中有以下代码块(这只是一个示例,问题不是关于拆分,而是抛出一个通用异常.另外,不能使用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");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。