Should I use the goto statement?

I have code similar to the following:

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; } 

Are there any better alternatives compared to using goto ? Or is this a good solution?

+4
source share
4 answers

It sounds like you really need a loop. I would write this as:

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

Instead, you can use the do / while ; I prefer direct while loops, but this is a personal preference, and I see how this might be more appropriate.

I would not use goto . This makes the code more complex.

Of course, if you really want an infinite loop, just put a try/catch inside the loop:

 while (true) { try { ... } catch (Exception) { ... } } 
+16
source

Goto very rarely suitable for use. Use will confuse 99 percent of people who look at your code and even technically correct use of it will significantly slow down the understanding of the code.

In most cases, code refactoring eliminates the need (or desire to use) Goto . That is, in your particular case, you can just move try/catch inside while(true) . Creating internal iteration code in a separate function is likely to make it even cleaner.

 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(); } } 
+10
source

It would seem to make sense to just move try / catch into a while loop. Then you can simply handle the error and the loop will continue, as usual, without having to route the control flow using labels and gotos.

0
source

Catching and restoring the state at each iteration, even if catching outside will work the same, here you are still in the loop, and you can decide whether you want to continue or break the loop.

SEE ALSO: Catching Exception wrong from the very beginning (what are you going to do if you catch a StackOverflowException or MemoryLeachException - EDIT: for example, check the documentation to see what you can actually catch ). Cut out the specific type of exception you expect to throw.

 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. } } 

for very smart in the comments: Why not catch the general exception

-2
source

Source: https://habr.com/ru/post/1444624/


All Articles