Capturing Ctrl-c in ruby

前端 未结 5 1648
慢半拍i
慢半拍i 2020-12-02 06:02

I was passed a long running legacy ruby program, which has numerous occurrences of

begin
  #dosomething
rescue Exception => e
  #halt the exception\'s pr         


        
5条回答
  •  孤街浪徒
    2020-12-02 06:24

    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.

提交回复
热议问题