Hegwin.Me

The hydra-universe twisting its body scaled in stars.

Ruby 2.5 allows rescue/ensure inside do/end blocks

Ruby 2.5 允许在do/end代码块中使用rescue

This article introduces a new feature of Ruby 2.5: in previous versions of Ruby if you needed to use rescue to catch and handle exceptions, you had to put the rescue in to the codes that might throw an exception in the "begin end" block. Since Ruby 2.5, you can use rescue in a normal "do end" block. Note that this feature is not backward compatible, and you will encounter errors if you are in Ruby 2.4.

In Ruby 2.4

(-1).upto(1).each do |i|
  p 8 / i
rescue e
  p e
end

You will get SyntaxError: unexpected keyword_rescue, expecting keyword_end.

In Ruby 2.5

(-1).upto(1).each do |i|
  p 8 / i
rescue e
  p e
end

You will get.:

-8
#<ZeroDivisionError: divided by 0>
8
< Back