我有一个代码,如果之前在代码中有错误,那么这些代码必须不能执行.我实际上使用一个名为bool的bool变量EndProg,如果设置为true,将指示程序避免执行某些代码部分.
我的问题是我不想使用这种方法而我更愿意使用goto它,因为它会使程序跳转到清理部分并避免EndProg多次检查值.
另一个问题是我在StackOverflow和其他网站上的许多页面上阅读过使用goto被认为是一种不好的做法,并且它可能使代码更难以阅读或创建错误.
我的代码很简单,我只需要使用一个标签,所以我怀疑这会产生问题; 但是我想知道是否有其他方法可以做我想要的而不创建执行清理任务或使用的函数return(因为,例如,我需要多次编写清理代码)而且我也不想在多个地方编写相同的大清理代码,然后使用return或执行其他操作.
我不想增加代码行数,也不想使用return或使用很多if也不检查状态变量的值.你会推荐什么 ?
这是一段代码:
bool EndProg=false;
/*
Lot of code that can set EndProg to true
*/
ClassType ClassName;
if(!EndProg && LoadConf(&ConfFilePath,&ClassName)==0)
{
int fildes=-1;
if(ClassName.abc) // bool
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath!=0)strcpy(ClassName.FilePath,"file.ext");
else EndProg=true;
}
if(!EndProg && mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if(errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We continue, later we will try to open this file */
}
else EndProg=true;
}
if(!EndProg && (fildes=open(ClassName.FilePath,O_RDWR))==-1)EndProg=true;
}
/*
Lot of code that will check if EndProg == true
*/
}
delete[] ClassName.FilePath;
delete[] ConfFilePath;
Run Code Online (Sandbox Code Playgroud)
我想做的是:
bool EndProg=false;
/*
Lot of code that can set EndProg to true
*/
ClassType ClassName;
if(LoadConf(&ConfFilePath,&ClassName)==0)
{
int fildes=-1;
if(ClassName.abc) // bool
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath==0)goto cleanup;
strcpy(ClassName.FilePath,"file.ext");
}
if(mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if(errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We continue, later we will try to open this file */
}
else goto cleanup;
}
if((fildes=open(ClassName.FilePath,O_RDWR))==-1)goto cleanup;
}
/*
Lot of code that will check if EndProg == true
*/
}
cleanup:
delete[] ClassName.FilePath;
delete[] ConfFilePath;
Run Code Online (Sandbox Code Playgroud)
你可以看到它并不难理解,即使搜索标签对某人来说可能是个问题,也不适合我.我不打算公开代码.
更新:
我决定使用异常,它适用于原始代码的某些部分.但我怀疑这将更容易在更复杂的部分实施.谢谢你的回答.
既然你已经标记了这个问题,c++那么我会使用异常和try catch块.
您可以在SO和其他网站上找到有关该主题的大量有用信息:
这是一个非常基础的教程.
这里有一个很好的基本常见问题解答,也可以帮到你.
基本上没有什么可担心的,例外不是神秘的,事实上当你掌握它时更有意义.因为基本上这个概念使您能够完全达到您想要的效果:
可以通过相同的错误处理代码处理的几个陷阱.
编辑:例如,如果我将mkfifo等等移动到一个函数中(通常为每个定义良好的逻辑块创建一个函数更清晰,更可读)并且有类似的东西
这只是一个草图,为您提供一个大致的想法:
#include <exception>
functionThatDoesMakeFifo(...){
// check which ever conditions you want to check after mkfifo
// if one of them goes wrong just do:
throw std::exception();
}
// this is inside your function:
ClassType ClassName;
try{
ClassName.FilePath = new char[9](); // even though I'd use a string...
.
.
. // rest of the code
} catch(std::exception &e){
delete [] ClassName.FilePath;
delete [] ConfFilePath;
ClassName.FilePath = NULL; // not mandatory just my habit
ConfFilePath = NULL;
}
Run Code Online (Sandbox Code Playgroud)