Try Catch With Ruby Blocks

last modified: January 30, 2009

RenameMe to ContinuationsInRuby ?

People on BlocksInPython want to see TryCatch implemented in RubyLanguage. I won't dive in a SchemeLanguage-like continuation-based ErrorHandling, just note that this (somewhat) already exists:

def routine(n)
 puts n
 throw :done if n <= 0
 routine(n-1)
end

catch(:done) do
 routine(3)
end

RubyLanguage's 'throw' and 'catch' is GoTo. GoTo has its uses, but for conventional ErrorHandling use 'raise' and 'rescue':

def factorial(n)
  raise ArgumentError, "factorial arg must be >= 0: #{n}," unless n >= 0
  return 1 if n.zero?
  (1..n).inject(1) { |product, i| product * i },
end

while true
  print 'Enter a number (-1 to quit): '
  n = gets.to_i
  exit if n == -1
  begin
    puts "#{n},! = #{factorial(n)},"
  rescue ArgumentError => e
    puts e
  end
end

See also ContinuationsAreGotos, ContinuationsInPython


CategoryRuby


Loading...