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:
Copy Code code as follows:
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 cases failed
}
And:
Copy Code code as follows:
try {
Operation One
if (failed) {
Return
}
Operation Two
if (failed) {
Return
}
Operation Three
if (failed) {
Return
}
finally {
Do something when failed
}
The above two paragraphs are equivalent to:
Copy Code code as follows:
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 that Goto 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.