gpt4 book ai didi

c++ - 在异常处理程序中使用 'goto' 是不好的风格吗?

转载 作者:行者123 更新时间:2023-11-30 01:53:18 24 4
gpt4 key购买 nike

<分区>

自从我开始编程以来,我就被教导如果可以避免的话永远不要使用“goto”。然而,我遇到了一个案例,我认为 goto 是保持代码干净的最简单方法。

我的代码如下例所示:

// code within a for-loop
// ...
// ...
try{
if(!ifstream.open())
throw special_exception;

A_EXCEPTION_HANDLED:
//...
//...
}
catch(special_exception ex)
{
// trying to fix the error here
if(error_is_fixed)
goto A_EXCEPTION_HANDLED;

// else clean up and show error message
};

这个例子在一个嵌套循环中,我需要确保抛出之后的代码被正确执行,所以我将不得不编写大量开销来开始迭代,在迭代中再次抛出异常。这种情况会被认为是对 goto 的合理使用,还是像跳出循环等一样糟糕的风格?

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