Explain Ruby on Rails Exception Handling

Technology CommunityCategory: Ruby on RailsExplain Ruby on Rails Exception Handling
VietMX Staff asked 3 years ago

The general flow of begin/rescue/else/ensure/end looks like this:

begin
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
rescue SomeOtherException => some_other_variable
  # code that deals with some other exception
else
  # code that runs only if *no* exception was raised
ensure
  # ensure that this code always runs, no matter what
  # does not change the final value of the block
end

You can leave out rescueensure or else.

Some blocks form implicit exception blocks. For example, method definitions are implicitly also exception blocks, like:

def foo
  # ...
rescue
  # ...
end