Search code examples
rubyloggingerror-handlingblockrescue

Ruby exception handling in else block


So I have classic ruby exception handling:

begin
    # do work here
rescue SafeShutdown => e
    # prevent loss of data and safely shutdown
rescue SystemExit => e
    # print #{e} and continue
else
    # how can I get #{e} here to get error message
    # so I can behave like in previous rescue
    # 
    # print #{e} and continue
end

My question is how can I get "e" to print out in logger in else part of the block.


Solution

  • In the begin rescue block else is called only when no exception occurs, i.e. no error was thrown. Try this:

    begin
      # do work here
    rescue SafeShutdown => e
      # print e
    rescue SystemExit => e
      # print e
    else
      # this will only run when no exceptions are thrown
    ensure
      # this will always run
    end