0

It is strongly advised that we should not do:

rescue Exception

but instead use at least:

rescue StandardError

because otherwise, we might also catch (for instance) signals which are intended to (legally) terminate our program.

But how about

... 
rescue Exception => e
  begin # Just in case I get another exception when writing the log
    mylogfile.puts("Exception #{e} occured")
  rescue Exception
  end
  raise e
end
...

Should this also considered dangerous? After all, I'm re-raising the same exception, plus I have some evidence of what has happened, in my log.

Community
  • 1
  • 1
user1934428
  • 19,864
  • 7
  • 42
  • 87
  • 5
    Log and throw is generally considered a bad idea (http://stackoverflow.com/questions/6639963/why-is-log-and-throw-condsidered-an-anti-pattern) – Andrew Oct 13 '15 at 15:39
  • When your program crashes, it prints details to the stdout. Isn't that enough? – Sergio Tulentsev Oct 13 '15 at 15:45
  • 1
    Besides all the comments above, how would you suspect your code to print a log message on e.g. `OutOfMemory`? – Aleksei Matiushkin Oct 13 '15 at 16:01
  • @Sergio Tulentsev: Of course one could redirect stderr and stdout to some file, but it's more convenient to have the message in the log file. – user1934428 Oct 14 '15 at 09:18
  • @mudasobw: Not really a problem. In this case, the logging would also raise an exception. This would be ignored, and then `raise e` would be executed. This would write the exception to stderr and then, as Sergio Tulentsev observed, it can be observed too. Just in the majority of cases, where the original exception does NOT affect logging, it would occur in the logfile. – user1934428 Oct 14 '15 at 09:22
  • @Andrew Piliser: Thank you for pointing out this thread on stackoverflow. From this discussion, I can see that there are cases where this pattern made makes sense, but we can not say that it makes sense in general. In my case (maybe I should have mentioned it), I have a logging framework which can generate ENTRY/EXIT log events for functions (which then are nicely paired up in the log), and an exception might break this concept. Therefore I certainly want to see StandardError exceptions in my log (and how to be propagated upwards), but I'm not sure about Exceptions in general. – user1934428 Oct 14 '15 at 09:30

0 Answers0