在Catch子句中使用GoTo重用Try语句?

问题描述 投票:0回答:2

我正在研究一些代码示例,并且看到了以下示例的类似变化,其中一个让我非常好奇。

goto_tag放在try声明之前。这完全有道理,它再次穿过try

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
}   

但是,随着以下内容呈现给我,我不明白。当goto_tag被放置在try语句中时,从catch块中调用。

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
}   

try块复活了吗?或者这两个例子在功能上是否相同,或者这是一个完全非法的操作,甚至不会编译?

这完全出于好奇,当然我更喜欢第一个例子,如果他们中的任何一个......

感谢您的任何见解!!

c# try-catch
2个回答
2
投票

要真正回答你的问题:

不,这些都不一样。

第一个例子将编译;第二个是非法的。

(你是否应该编写这样的代码是一个不同的问题......当然,如果你能帮助它,你就不应该这样做。)


1
投票

你可以实现一个简单的while而不是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.       
  } 
}
© www.soinside.com 2019 - 2024. All rights reserved.