gpt4 book ai didi

c++ - 出于一般原因抛出异常c++

转载 作者:可可西里 更新时间:2023-11-01 18:14:59 25 4
gpt4 key购买 nike

我的构造函数中有以下代码块(这只是一个示例,问题不是关于split,而是关于throwing a generic exception。另外, 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");

关于c++ - 出于一般原因抛出异常c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11635281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com