文件系统异常处理中的Goto语句

问题描述 投票:0回答:2
save:
try
{
    s.Save();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
    FSErrorDialog fsError = new(ex, FSVerb.Access, new FileInfo(path), Button.Retry, Button.Ignore);
    if (fsError.ShowDialog().ClickedButton == Button.Retry)
    {
        goto save;
    }
}

Save()
方法将对象保存到磁盘。 如果发生外部异常,系统会提示用户重试操作,以避免丢失未保存的数据。

我知道我可以使用带有break语句的

while (true)
循环,但我认为goto方法更具可读性。它还可以节省缩进级别。

我害怕使用 goto。

这是 goto 语句的合法使用吗?

c# exception filesystems goto
2个回答
2
投票

我建议声明一个布尔值来跟踪您是否应该重试。这样你就可以使用 do/while 循环:

bool shouldRetry;
do
{
    try
    {
        s.Save();
        shouldRetry = false;
    }
    catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
    {
        FSErrorDialog fsError = new(ex, FSVerb.Access, new FileInfo(AppDirectory.Scripts.Join(s.FilePath)), Button.Retry, Button.Ignore);
        shouldRetry = fsError.ShowDialog().ClickedButton == Button.Retry;
    }
}
while (shouldRetry);

为了解决您在问题中提到的“更具可读性”方面,我认为这更具可读性,原因有两个:

  1. 我们使用的是明确存在为循环的东西,因此从一开始就很清楚循环是可能的。您无需找到
    goto
    即可确定它是循环的。
  2. 变量名
    shouldRetry
    非常清楚地说明了为什么我们要循环:因为我们需要重试。

1
投票

我建议无限循环;我们循环直到没有例外或者当我们决定停止尝试时:

while (true) {
  try {
    s.Save();

    break; // No more looping (success)
  }
  catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) {
    FSErrorDialog fsError = new(ex, FSVerb.Access, new FileInfo(path), Button.Retry, Button.Ignore);
    
    if (fsError.ShowDialog().ClickedButton != Button.Retry)
      break; // No more looping (no more tries)  
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.