Capturing Ctrl-c in ruby

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

rescue Exception => e
  # ...
end

to

rescue StandardError => e
  # ...
end

for those you can’t change to StandardError, re-raise the exception:

rescue Exception => e
  # ...
  raise
end

or, at the very least, re-raise SystemExit and Interrupt

rescue SystemExit, Interrupt
  raise
rescue Exception => e
  #...
end

Any custom exceptions you have made should derive from StandardError, not Exception.

Leave a Comment