使用嵌套的"try/finally". “尝试/除外"陈述 [英] Use of nested "try/finally" "try/except" statements

查看:145
本文介绍了使用嵌套的"try/finally". “尝试/除外"陈述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在StackOverflow上看到了以下代码:

I have seen this code posted here on StackOverflow:

with TDownloadURL.Create(nil) do
  try
    URL := 'myurltodownload.com';
    filename := 'locationtosaveto';
    try
      ExecuteTarget(nil);
    except
      result := false;
    end;
    if not FileExists(filename) then
      result := false;
  finally
    free;
  end;

不能简化为:

 Result:= FALSE;               <--------- Compiler complains
 DeleteFile(Dest);
 dl:= TDownloadURL.Create(NIL);
 TRY
   dl.URL:= URL;
   dl.FileName:= Dest;
   dl.ExecuteTarget(NIL);           
   Result:= FileExists(Dest);
 FINALLY
   dl.Free;
 END;

如果'ExecuteTarget'中发生错误,则最终结果:= ...将永远不会执行,因为该程序将直接跳转到'finally'.正确的?因此,该函数将返回FALSE.我在做错什么吗?

The final Result:= ... will never be executed if something went wrong in 'ExecuteTarget' be cause the program will jump directly to 'finally'. Right? So, the function will return FALSE. Am I doing something wrong?

PS:

  1. 我打算在线程中使用此代码.
  2. 我只是将函数放在Delphi中,编译器抱怨第一行:从未使用分配的值."

推荐答案

区别在于您的第二个示例将异常传递回调用方,而原始示例将异常捕获并返回false.我将这种编码风格描述为我不在乎它为什么失败,我只在乎它是否成功".在某些情况下(例如尝试下载更新),这可能是合理的.

The difference is that your second example passes exceptions back to the caller, while the original traps them and returns false. I'd characterise that style of coding as "I don't care why it failed, I only care whether it succeeded". Which can be reasonable in some cases (like trying to download an update).

因此,您的代码与原始代码大不相同-您希望调用方处理原始代码不会处理的异常.

So your code is very different from the original in that way - you are expecting the caller to handle exceptions that the original code does not.

此外,编译器的抱怨是因为您的代码中没有分支-如果工作和结果由第二个赋值确定,或者您有异常且Result不相关.

Also, the compiler complaint is because there's no branch in your code - either if works and result is determined by the second assignment or you have an exception and Result is irrelevant.

Result := FALSE; //   <--------- Compiler complains
DeleteFile(Dest);
dl := TDownloadURL.Create(nil);
try
   dl.URL := URL;
   dl.FileName := Dest;
   dl.ExecuteTarget(nil);
   Result := FileExists(Dest);
finally
   dl.Free;
end;

这篇关于使用嵌套的"try/finally". “尝试/除外"陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆