Once upon a time, Goto is how to let New bloom their superb skills
Once upon a time, Goto became the head of all evils.
Once upon a time, the Goto only example in the textbook will appear
There are too many reasons not to use Goto, but sometimes, we want to use the function of Goto, how to do.
With try/catch/finally, you can achieve the same equivalent goto function, look at two examples:
try {
//operation one
if (failed) {
throw Exception;
}
Operation two
if (failed) {
throw Exception;
}
Operation three
if (failed) {
throw Exception;
}
catch (Exception e) {
//do something when C ASEs failed
}
And:
try {
//operation one
if (failed) {return
;
}
Operation two
if (failed) {return
;
}
Operation three
if (failed) {return
;
}
} finally {
//does something when failed
}
The above two paragraphs are equivalent to:
Operation One
if (failed) {
goto when_failed;
}
Operation One
if (failed) {
goto when_failed;
}
Operation One
if (failed) {
goto when_failed;
}
When_failed:
//Do something when failed
Some violence in an unusual way, but it does help to achieve a function like Goto; using return and finally, though not very violent, is more difficult to control because it involves a return statement that executes after the finally block executes, so if you don't want to quit the program, This method might as well be controlled with exceptions.
In addition, break, continue is also a more powerful jump statements, especially break label and continue label, you can jump out of a layer of circulation or multi-layer cycle; However, it is important to note that the break can only be used in circular statements and switch statements, and continue can only be used in circular statements. So they have a lot of limitations.
This small example shows thatGoto is not just a statement, it is a kind of problem-solving thinking and programming habits, people who are accustomed to it, or want to use it, even if not Goto will write a similar goto logic out. The advantage is that it will be easier to help find the solution. Its faults are known to all. But we want to avoid is not only a goto statement, but this "jump-type" solution and programming habits.