Forwarding Forwarding - 2 months ago 6
Ruby Question

How to do something upon error in Ruby?

Say I do

.operator
on an array or something and
.operator
produces an error, how can I not have the program terminate and instead do something else, like
array[$i] << 'error'
.

Answer

Ruby provides exception handling via begin , rescue blocks. you may do the following

exception_array = []

begin 
  array.operator
rescue Exception => e
  exception_array << e
ensure
  # this line will execute irrespective of an
  # error happened or not
end

Lets breakdown the commands and the program flow

First your program try to execute the command in begin block. So if it raise any error, then it goes to rescue section

Exception is there to catch any type of exception. But you can specify the exception type you want too. Following is the ruby exception hierarchy from nicksiegers blog

Exception
    NoMemoryError
    ScriptError
        LoadError
        NotImplementedError
        SyntaxError
    SignalException
        Interrupt
    StandardError
        ArgumentError
        IOError
            EOFError
        IndexError
            StopIteration
        LocalJumpError
        NameError
            NoMethodError
        RangeError
            FloatDomainError
        RegexpError
        RuntimeError
        SecurityError
        SystemCallError
        SystemStackError
        ThreadError
        TypeError
        ZeroDivisionError
    SystemExit
    fatal 

So depending on the error type you can catch a specific error type if you want to

=> e part is assigning your error to a variable called e. You can rename this to anything you want.

The last part is ensure and this is optional, Ensure will execute no matter you get an error or not. So if you have something to get done, if an error happens or not, you can use ensure

This is a good read on ruby error handling