Logo

TODAY I LEARNED

Always use retry inside rescue blocks

Ruby includes a retry keyword that would bring execution back to the start of the current method while preserving scope. But what if you do this?

def my_method
  my_var = 1
  retry
end

That would fail with an Invalid retry, which is one of the few illegal statements in Ruby.

retry is only allowed inside rescue blocks.

def my_method
  my_var = 1
  raise Exception
rescue Exception
  retry
end

Learned by kevin-perez on Aug 16, 2022

973983 adforcodereview v3 0211021 c02 021121