我应该使用goto声明吗?

我有一段代码如下:

try { Work: while(true) { // Do some work repeatedly... } } catch(Exception) { // Exception caught and now I can not continue // to do my work properly // I have to reset the status before to continue to do my work ResetStatus(); // Now I can return to do my work goto Work; } 

与使用goto相比,有更好的选择吗? 或者这是一个很好的解决方案?

听起来你真的想要一个循环。 我把它写成:

 bool successful = false; while (!successful) { try { while(true) { // I hope you have a break in here somewhere... } successful = true; } catch (...) { ... } } 

您可能希望使用do / while循环; 我倾向于选择直接循环,但这是个人偏好,我可以看到它在这里更合适。

不会使用goto 。 它往往会使代码更难以遵循。

当然如果你真的想要一个无限循环,只需将try/catch放在循环中:

 while (true) { try { ... } catch (Exception) { ... } } 

Goto很少适合使用构造。 使用会使99%的人看到你的代码,甚至在技术上正确使用它会使代码的理解变得非常慢。

在大多数情况下,重构代码将消除goto需要(或希望使用)。 即在你的特殊情况下,你可以简单地移动try/catch内部while(true) 。 将迭代的内部代码转换为单独的函数可能会使它更加清晰。

 while(true) { try { // Do some work repeatedly... } catch(Exception) { // Exception caught and now I can not continue // to do my work properly // I have to reset the status before to continue to do my work ResetStatus(); } } 

将try / catch移动到while循环似乎更有意义。 然后你可以只处理错误,循环将继续正常,而不必使用标签和gotos路由控制流。

在每次迭代时捕获并恢复状态,即使捕获外部也会起作用,此处您仍处于循环中,您可以决定是继续还是中断循环。

另外:从一开始就捕获Exception是错误的(如果你捕获StackOverflowExceptionMemoryLeachException你打算做什么 – 编辑:这只是例如,检查文档以了解你可以捕获的内容 )。 捕获您希望抛出的具体类型的exception。

 while(true) { try { // Do some work repeatedly... } catch(FileNotFoundException) //or anything else which you REALLY expect. { // I have to reset the status before to continue to do my work ResetStatus(); //decide here if this is till OK to continue loop. Otherwise break. } } 

对于那些非常聪明的评论: 为什么不抓住一般例外