Exception Handling For Rails Developers

For rails developers here some key facts about exception handling. First
we enclose a distinctive code that may carry an exception in a
start-finish block and likewise we are able to use one or more rescue
clauses to inform Ruby the forms of exceptions we wish to handle. It’s
to be noted that the physique of a procedure definition is an implicit
start-finish block; the is not noted, and the entire body of the system
is discipline to exception dealing with, ending with the end of the
method.

The program excphandling.rb illustrates this:

excphandling.rb

def raise_and_rescue
begin
puts ‘I am the raise.’
raise ‘An error occured.’
puts ‘I am not the raise.’
rescue
puts ‘I am rescued.’
end
puts ‘I am the begin rescued.’
end
raise_and_rescue

The output is:

excphandling.rb
I am the raise.
I am rescued.
I am the begin rescued.
Exit code: 0

We can stack “rescue: clauses in a begin/rescue block. Always remember
any Exceptions that are not handled by one rescue clause will always
trickle down to the next:

begin

rescue OneTypeOfException

rescue AnotherTypeOfException

else

Other exceptions

end

For each rescue clause within the block, Ruby continually compares the
raised Exception against each of the parameters in flip. The fit will
succeed if the exception named in the rescue clause is the identical
because the style of the currently thrown exception, or is a superclass
of that exception. The code in an else clause is accomplished if the
code in the physique of the announcement runs to completion with out
exceptions. If an exception occurs, then the else clause will without
doubt no longer be performed. Using an else clause shouldn’t be
particularly long-established in Ruby.

The Exception category defines two methods that return details
concerning the exception. The message procedure returns a string that
may furnish human-readable details about what went wrong. The other
foremost system is backtrace. This method returns an array of strings
that represent the call stack at the point that the exception was
raised.