Hey you...person who stumbled upon this webpage in search of what the keywords begin and rescue mean in Ruby.


You're in for a quick explanation.


First, you need to understand this important point.


Your Ruby programs can trigger an error at any moment while they’re running.


When that happens…Ruby knows how to handle it...if you give it the opportunity to and like most decent Ruby programs, we want to handle those exceptions skillfully.

How to Handle Ruby Exceptions

How do you handle these exceptions?

You can wrap the code that raises the exception with a begin / rescue block.


Here’s how to do it…

The first section (begin), has the code that you’re going to run & that may raise an exception.

begin
  # code that has an error.
rescue
  # code that redirects if there's an error
end


An exception is raised when there's an error and the rescue clause 'rescues' the situation and that's what you want to happen when an exception is raised.

Using Rescue clause without begin keyword

Sometimes you don’t need to use the begin keyword.


There are cases where you can omit it like inside methods & blocks.

For instance...

def get_null_device
  IO.sysopen('/dev/null')
rescue Errno::ENOENT
  puts "Can't open IO device."
end

The method definition itself does the work of begin, so you can omit it.


You can also do this with other blocks.

For instance...

["1.jpg", "2.jpg", "3.jpg"].map do |f|
  IO.sysopen(f)
rescue Errno::ENOENT
  puts "Can't open IO device: #{f}."
end


And there you have it! The rescue clause in Ruby explained in less than ten minutes!