October 24, 2017
This blog is part of our Ruby 2.5 series.
irb> array_from_user = [4, 2, 0, 1]
=> [4, 2, 0, 1]
irb> array_from_user.each do |number|
irb> p 10 / number
irb> rescue ZeroDivisionError => exception
irb> p exception
irb> next
irb> end
SyntaxError: (irb):4: syntax error, unexpected keyword_rescue,
expecting keyword_end
rescue ZeroDivisionError => exception
^
Ruby 2.4 throws an error when we try to use rescue/else/ensure inside do/end blocks.
irb> array_from_user = [4, 2, 0, 1]
=> [4, 2, 0, 1]
irb> array_from_user.each do |number|
irb> p 10 / number
irb> rescue ZeroDivisionError => exception
irb> p exception
irb> next
irb> end
2
5
#<ZeroDivisionError: divided by 0>
10
=> [4, 2, 0, 1]
Ruby 2.5 supports rescue/else/ensure inside do/end blocks.
Here is relevant commit and discussion.
If this blog was helpful, check out our full blog archive.