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

后端 未结 2 580
逝去的感伤
逝去的感伤 2020-12-31 12:48

Consider this begin-rescue-ensure block:

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


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 12:55

    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
    

提交回复
热议问题