Ruby: try, catch, finally, throw, rescue, raise

begin-rescue-end

Instead of a try-catch statement from other languages, Ruby uses begin-rescue-end. The rescue block (aka catch) is executed when an exception is thrown from the begin section:

begin
  compute_median(scores)
rescue
  handle_exception
end

If the begin-rescue-end statement is inside a function, you can leave out the begin and end:

def compute_average(scores)
  do_work
rescue
  handle_exception
end

You can rescue (aka catch) exceptions by Class:

begin
  compute_median(scores)
rescue NotANumberError => e
  handle_exception(e)
end

Warning! Ruby has a catch keyword, but it does not do the same thing as catch from other languages.

After rescuing an exception, you can raise it (aka throw):

begin
  compute_median(scores)
rescue NotANumberError => e
  handle_exception(e)
  raise e
end

Warning! Ruby has a throw keyword, but it does not do the same thing as throw from other languages.

begin-rescue-ensure-end

begin-rescue-ensure-end is the equivalent of try-catch-finally from other languages. The ensure block is executed regardless whether the rescue block was executed or not.

begin
  compute_median(scores)
rescue NotANumberError => e
  handle_exception(e)
  raise e
ensure
  do_this_always
end

begin-rescue-else-end

begin-rescue-else-end is NOT the same as try-catch-finally in other languages. The else block is only executed if the rescue block was not. So the else is NOT equivalent to finally:

begin
  compute_median(scores)
rescue NotANumberError => e
  handle_exception(e)
  raise e
else
  handle_success
end