我的构造函数中有以下代码块(这只是一个示例,问题不在于split,而是抛出一个通用异常.此外,不能使用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.
}
}
Run Code Online (Sandbox Code Playgroud)
我想要的是如果目录不存在而无法创建,则抛出异常.我想抛出一个通用异常,我怎么能这样做呢C++?PS:dest具有以下格式:
dest = /usr/var/temp/current/tree
Run Code Online (Sandbox Code Playgroud)
Per*_*est 11
请检查这个答案.这解释了如何使用自己的异常类
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.
}
}
Run Code Online (Sandbox Code Playgroud)
此外,如果您不想要自己的课程,您可以简单地执行此操作
throw std::runtime_error("Error creating the directory\n");
Run Code Online (Sandbox Code Playgroud)
您的使用strtok是不正确 -它需要一个char*,因为它修改字符串,但不允许修改的结果.c_str()上std::string.使用C样式演员(这里表现得像const_cast)的需要是一个很大的警告.
你可以通过使用boost文件系统巧妙地回避这个和路径分离器可移植性的东西,每当它发布时它很可能出现在TR2中.例如:
#include <iostream>
#include <boost/filesystem.hpp>
int main() {
boost::filesystem::path path ("/tmp/foo/bar/test");
try {
boost::filesystem::create_directories(path);
}
catch (const boost::filesystem::filesystem_error& ex) {
std::cout << "Ooops\n";
}
}
Run Code Online (Sandbox Code Playgroud)
拆分平台分隔符上的路径,根据需要创建目录,如果失败则抛出异常.