Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

People also ask

How do you rescue in Ruby?

A raised exception can be rescued to prevent it from crashing your application once it reaches the top of the call stack. In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from.

How does rescue work in Ruby?

The code between “begin” and “rescue” is where a probable exception might occur. If an exception occurs, the rescue block will execute. You should try to be specific about what exception you're rescuing because it's considered a bad practice to capture all exceptions.

What is exception handling in Ruby?

In Ruby, exception handling is a process which describes a way to handle the error raised in a program. Here, error means an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program's instructions.

How do you write try catch in Ruby?

Ruby Internal try catch (raise and rescue) In case exceptions happen in the begin block it will halt and control will go between rescue and end, and we can return a valid message for the user in case of exceptions. Every time for a rescue statement Ruby checks and compares the exception raised for each parameter.


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

def foo
  ...
rescue
  ...
end

You can also rescue inline:

1 + "str" rescue "EXCEPTION!"

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


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!


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