当我在“救援"中“重试"时,Ruby无法“确保" [英] Ruby does not 'ensure' when I 'retry' in 'rescue'

查看:71
本文介绍了当我在“救援"中“重试"时,Ruby无法“确保"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下开始救援确保块:

Consider this begin-rescue-ensure block:

attempts=0
begin
  make_service_call()
rescue Exception
  retry unless attempts>2
  exit -1
ensure
  attemps += 1
end

如果按原样运行该代码,则会引发异常,因为没有名为"make_service_call()"的函数.因此,它重试.但这会陷入无限循环,因为控制不会因为重试"而转到确保"状态.无论开始"还是救援"发生什么情况,都不能确保"模块的一部分来确保其中的代码被执行吗?

If you run that code as it is, it raises an exception because there is no function called 'make_service_call()'. So, it retries. But it would be stuck in infinite loop because the control never goes to 'ensure' because of the 'retry'. Shouldn't 'ensure' part of the block ensure that the code in it gets executed no matter what happens in 'begin' or 'rescue'?

我当然可以在'begin'中增加计数-这不是重点.我只是在问有关确保"的问题,以使其更加清晰.

Of course I can increment the count in 'begin' - that's not the point. I am just asking the question about 'ensure' to get some clarity.

推荐答案

ensure部分在离开begin语句时(无论如何)执行,但是当您retry时,您只是在内部移动该语句,以便确保部分不会被执行.

The ensure section is executed when leaving the begin statement (by any means) but when you retry, you're just moving around inside the statement so the ensure section will not be executed.

尝试使用此示例版本,以更好地了解发生的情况:

Try this version of your example to get a better idea of what's going on:

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

这篇关于当我在“救援"中“重试"时,Ruby无法“确保"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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