Once upon a time, how powerful goto was to let the cool man Bloom their superb technologies. Once upon a time, goto became the first of all evil, the goto example only appears in the textbook. There are too many reasons not to use goto, but sometimes we want to use the goto function. What should we do? You can use trycatchfinally to implement the same goto function.
Once upon a time, how powerful goto was to let the cool man Bloom their superb technologies. Once upon a time, goto became the first of all evil, the goto example only appears in the textbook. There are too many reasons not to use goto, but sometimes we want to use the goto function. What should we do? Use try/catch/finally to implement the same goto function.
Once upon a time, goto was so amazing that cool people could bloom with their superb technologies.
Once upon a time, goto became the first of all evil
Once upon a time, goto only appeared in the example in the textbook
There are too many reasons not to use goto, but sometimes we want to use the goto function. What should we do?
You can use try/catch/finally to implement the same goto function. Here are 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 cases failed}
And:
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:
// 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
The exception method is a bit violent, but it does help to implement a function similar to goto. Although return and finally statements are not very violent, they are difficult to control because return statements are involved, it will be executed after the finally block is executed. Therefore, if you do not want to exit the program, it is better to use exceptions to control this method.
In addition, break and continue are also powerful jump statements. In particular, break label and continue label can jump out of one or more loops; note that break can only be used in loop statements and switch statements, and continue can only be used in loop statements. Therefore, they have great limitations.
This small example shows that,Goto is not just a statement, it is a way of thinking and programming habits to solve the problem,People who are used to it, or who want to use it, will write similar goto logic even if they don't use goto. Its advantage is that it is easier to help find a solution. Its shortcomings are also widely known. But what we need to avoid is not just a goto statement, but the solution and programming habits of this "jump type.