-1

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.

shivam
  • 16,048
  • 3
  • 56
  • 71
Jakub Zak
  • 1,212
  • 6
  • 32
  • 53
  • How do you suggest getting access to the exception in the `else` clause, which is only executed when there is no exception? – Jörg W Mittag Jul 08 '15 at 16:32

1 Answers1

2

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
Piotr Kruczek
  • 2,384
  • 11
  • 18
  • I then don't really get function of "else" in there, I though else behaves as a default for any other exception. I had completely misunderstood the else behaviour in that block. – Jakub Zak Jul 08 '15 at 14:52
  • You could use `rescue Exception => e` to catch all errors, but it's highly unrecommended. More info [here](http://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby) – Piotr Kruczek Jul 08 '15 at 14:54
  • Thank you that is very helpful... :) – Jakub Zak Jul 08 '15 at 14:58