in Hacking

Ruby’s “Begin Rescue” and “Try and Catch”

Thanks to the book "Programming Language Pragmatics"
Programming Language Pragmatics
I'm beginning to appreciate Ruby's different notation for exception handling.

A sample:

begin
  value = 7 / 0
rescue
  print "Something went wrong! This is an error" 
end

The code above is to catch an exception. (In Java or C++ you would use try and catch)

Ruby also has got try and catch, but this isn't used for exception handling. It is used for implementing "Multi Level Returns".
A sample:

def search( name )
  # .. some fancy code here ..
  if filename.contains( name ) throw :found_it, filename
end

result = catch :found_it do
  search "one"
  search "two"
  search "three"
  false
end

In the sample above, result will be filled with the found filename. This can be
with the keyword "one", "two" or "three". If nothing is found result is filled with false. (the last value in the catch block)

I don't think I need the catch construct very much, but it's a nice feature!

Share