Ruby Language Handling an exception


Example

Use the begin/rescue block to catch (rescue) an exception and handle it:

begin
  # an execution that may fail
rescue
  # something to execute in case of failure
end

A rescue clause is analogous to a catch block in a curly brace language like C# or Java.

A bare rescue like this rescues StandardError.

Note: Take care to avoid catching Exception instead of the default StandardError. The Exception class includes SystemExit and NoMemoryError and other serious exceptions that you usually don't want to catch. Always consider catching StandardError (the default) instead.

You can also specify the exception class that should be rescued:

begin
  # an excecution that may fail
rescue CustomError
  # something to execute in case of CustomError
  # or descendant
end

This rescue clause will not catch any exception that is not a CustomError.

You can also store the exception in a specific variable:

begin
  # an excecution that may fail
rescue CustomError => error
  # error contains the exception
  puts error.message # provide human-readable details about what went wrong.
  puts error.backtrace.inspect # return an array of strings that represent the call stack
end

If you failed to handle an exception, you can raise it any time in a rescue block.

begin
   #here goes your code
rescue => e
    #failed to handle 
    raise e
end

If you want to retry your begin block, call retry:

begin
   #here goes your code
rescue StandardError => e
   #for some reason you want to retry you code
   retry
end

You can be stuck in a loop if you catch an exception in every retry. To avoid this, limit your retry_count to a certain number of tries.

retry_count = 0
begin
      # an excecution that may fail
rescue
    if retry_count < 5
        retry_count = retry_count + 1
        retry
    else
        #retry limit exceeds, do something else
    end

You can also provide an else block or an ensure block. An else block will be executed when the begin block completes without an exception thrown. An ensure block will always be executed. An ensure block is analogous to a finally block in a curly brace language like C# or Java.

begin
  # an execution that may fail
rescue
  # something to execute in case of failure
else
  # something to execute in case of success
ensure
  # something to always execute
end

If you are inside a def, module or class block, there is no need to use the begin statement.

def foo
    ...
rescue
    ...
end