Ruby does not 'ensure' when I 'retry' in 'rescue'

雨燕双飞 提交于 2019-11-30 14:04:42

问题


Consider this begin-rescue-ensure block:

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

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'?

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.


回答1:


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



回答2:


ensure code is executed once, just before the code block exits and it will be called at that time.

But because of the unless attempts>2 condition, and the fact that ensure will only be called "just before the code exits" (e.g. due to exit -1) the attempts += 1 will not be executed, and so there is an infinite loop.

ensure is like __finally in C++ : you could catch the exception and then use a goto : but finally will not be called until the function is actually about to exit.



来源:https://stackoverflow.com/questions/6223518/ruby-does-not-ensure-when-i-retry-in-rescue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!