I was passed a long running legacy ruby program, which has numerous occurrences of
begin
#dosomething
rescue Exception => e
#halt the exception's progress
end
throughout it.
Without tracking down every single possible exception these each could be handling (at least not immediately), I'd still like to be able to shut it down at times with CtrlC.
And I'd like to do so in a way which only adds to the code (so I don't affect the existing behavior, or miss an otherwise caught exception in the middle of a run.)
[CtrlC is SIGINT, or SystemExit, which appears to be equivalent to SignalException.new("INT")
in Ruby's exception handling system. class SignalException < Exception
, which is why this problem comes up.]
The code I would like to have written would be:
begin
#dosomething
rescue SignalException => e
raise e
rescue Exception => e
#halt the exception's progress
end
EDIT: This code works, as long as you get the class of the exception you want to trap correct. That's either SystemExit, Interrupt, or IRB::Abort as below.
If you can wrap your whole program you can do something like the following:
This basically has CtrlC use catch/throw instead of exception handling, so unless the existing code already has a catch :ctrl_c in it, it should be fine.
Alternatively you can do a
trap("SIGINT") { exit! }
.exit!
exits immediately, it does not raise an exception so the code can't accidentally catch it.I am using
ensure
to great effect! This is for things you want to have happen when your stuff ends no matter why it ends.If you can't wrap your whole application in a
begin ... rescue
block (e.g., Thor) you can just trapSIGINT
:130 is a standard exit code.
The problem is that when a Ruby program ends, it does so by raising SystemExit. When a control-C comes in, it raises Interrupt. Since both SystemExit and Interrupt derive from Exception, your exception handling is stopping the exit or interrupt in its tracks. Here's the fix:
Wherever you can, change
to
for those you can't change to StandardError, re-raise the exception:
or, at the very least, re-raise SystemExit and Interrupt
Any custom exceptions you have made should derive from StandardError, not Exception.
Handling Ctrl-C cleanly in Ruby the ZeroMQ way:
Source