I am examining some code examples and have seen similar variation to the following examples, one of them made me very curious.
When a goto_tag
is placed before a try
statement. This makes complete sense and it just runs through the try
again.
retry_tag: //the goto tag to re-attempt to copy a file
try {
fileInfo.CopyTo( toAbsolutePath + fileInfo.Name, true ); //THIS LINE MIGHT FAIL IF BUSY
} catch {
Thread.Sleep(500); //wait a little time for file to become available.
goto retry_tag; //go back and re-attempt to copy
}
However, as the following was presented to me I did not understand it. When a goto_tag
is placed within the try
statement, and is called from within the catch
block.
try {
retry_tag: //the goto tag to re-attempt to copy a file
fileInfo.CopyTo( toAbsolutePath + fileInfo.Name, true ); //THIS LINE MIGHT FAIL IF BUSY
} catch {
Thread.Sleep(500); //wait a little time for file to become available.
goto retry_tag; //go back and re-attempt to copy
}
Is the try
block resurrected? Or are the two examples functionally identical, or is this an completely illegal operation and won't even compile?
This is all purely out of curiosity, and of course I would prefer the first example, if either of them..
Thanks for any insight!!
To actually answer your question:
No, these are not the same.
The first example will compile; the second is illegal.
(The matter of whether you should write code like this is a different question... and off course, you should not if you can help it.)
You can implement a simple while
instead of goto
:
// loop until ...
while (true) {
try {
fileInfo.CopyTo(Path.Combine(toAbsolutePath, fileInfo.Name), true);
// ... file copied
break;
}
catch (IOException) {
Thread.Sleep(500); //wait a little time for file to become available.
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.