How does one use rescue in Ruby without the begin and end block

Ruby

Ruby Problem Overview


I know of the standard technique of having a begin rescue end

How does one just use the rescue block on its own.

How does it work and how does it know which code is being monitored?

Ruby Solutions


Solution 1 - Ruby

A method "def" can serve as a "begin" statement:

def foo
  ...
rescue
  ...
end

Solution 2 - Ruby

You can also rescue inline:

1 + "str" rescue "EXCEPTION!"

will print out "EXCEPTION!" since 'String can't be coerced into Fixnum'

Solution 3 - Ruby

I'm using the def / rescue combination a lot with ActiveRecord validations:

def create
   @person = Person.new(params[:person])
   @person.save!
   redirect_to @person
rescue ActiveRecord::RecordInvalid
   render :action => :new
end

I think this is very lean code!

Solution 4 - Ruby

Example:

begin
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
ensure
  # ensure that this code always runs
end

Here, def as a begin statement:

def
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
ensure
  # ensure that this code always runs
end

Solution 5 - Ruby

Bonus! You can also do this with other sorts of blocks. E.g.:

[1, 2, 3].each do |i|
  if i == 2
    raise
  else
    puts i
  end
rescue
  puts 'got an exception'
end

Outputs this in irb:

1
got an exception
3
 => [1, 2, 3]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSidView Question on Stackoverflow
Solution 1 - Rubyalex.zherdevView Answer on Stackoverflow
Solution 2 - RubypekuView Answer on Stackoverflow
Solution 3 - RubyEdwin V.View Answer on Stackoverflow
Solution 4 - RubyHieu LeView Answer on Stackoverflow
Solution 5 - RubyPurplejacketView Answer on Stackoverflow