O'Reilly logo

Learning Sinatra by Manoj Sehrawat, Sudeep Agarwal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Exception handling

One of the more important tasks of writing code is handling exceptions. The exception handling block can be defined by the following structure:

begin
  # statements
rescue
  # handle error
else
  # statements to be executed if there are no errors
ensure
  # statements to be executed whether an error occurred or not
end

We can also use the raise statement to explicitly raise an exception.

This will be clearer by the following example:

begin
  for i in [1, 2, 3, 4, 5]
    raise if i == 4
    puts i
  end
rescue
  puts "Reached 4"
  next
else
  puts "No errors"
ensure
  puts "Iteration completed."
end

The output of the code will be as follows:

1
2
3
Reached 4
Iteration completed.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required