Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby没有';确保';当我';重试';在';救援';_Ruby_Rescue - Fatal编程技术网

Ruby没有';确保';当我';重试';在';救援';

Ruby没有';确保';当我';重试';在';救援';,ruby,rescue,Ruby,Rescue,考虑以下情况: attempts=0 begin make_service_call() rescue Exception retry unless attempts>2 exit -1 ensure attemps += 1 end 如果按原样运行该代码,则会引发异常,因为没有名为“make_service_call()”的函数。所以,它重试。但它将被卡在无限循环中,因为控件由于“重试”而从不转到“确保”。块的“确保”部分不应该确保无论在“开始”或“救援”中发生什么都能

考虑以下情况:

attempts=0
begin
  make_service_call()
rescue Exception
  retry unless attempts>2
  exit -1
ensure
  attemps += 1
end
如果按原样运行该代码,则会引发异常,因为没有名为“make_service_call()”的函数。所以,它重试。但它将被卡在无限循环中,因为控件由于“重试”而从不转到“确保”。块的“确保”部分不应该确保无论在“开始”或“救援”中发生什么都能执行其中的代码吗


当然,我可以在“开始”中增加计数-这不是重点。我只是想问一个关于“确保”的问题,以便弄清楚。

在离开
begin
语句时执行
sure
部分(通过任何方式),但当您
重试时,您只是在语句内部移动,因此确保部分不会执行

尝试此版本的示例,以更好地了解发生了什么:

attempts = 0
begin
  make_service_call()
rescue Exception
  attempts += 1
  retry unless attempts > 2
  exit -1
ensure
  puts "ensure! #{attempts}"
end

确保
代码在代码块退出之前执行一次,并在此时调用它

但是由于
除非尝试次数>2
条件,以及
确保
只会在“代码退出前”调用(例如,由于
退出-1
),将不会执行
尝试次数+=1
,因此存在无限循环

<>代码>确保在C++中类似<代码>最后,:您可以<代码> catch < /COD>异常,然后使用<代码> Goto :但<>代码>最后/>代码>直到函数即将退出。