以红宝石捕获Ctrl-c [英] Capturing Ctrl-c in ruby

查看:152
本文介绍了以红宝石捕获Ctrl-c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过了一个长期的遗留的红宝石程序,它有许多次发生的

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

没有跟踪每个可能的异常,每个可能会处理(至少不是立即),我仍然希望能够关闭它, kbd> Ctrl C

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.)

[ Ctrl C 是在Ruby的异常处理系统中看起来相当于 SignalException.new(INT)的SIGINT或SystemExit。 class SignalException<例外,这就是为什么会出现这个问题。]

[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.]

我想写的代码是:

begin
  #dosomething
rescue SignalException => e
  raise e
rescue Exception => e
  #halt the exception's progress
end

编辑:代码工作,只要你得到你想陷阱正确的异常的类。这是SystemExit,Interrupt或IRB :: Abort,如下所示。

推荐答案

问题是,当一个Ruby程序结束,它通过提高SystemExit 来实现。当控件C进入时,它引发中断。由于 ,您的异常处理将阻止其轨迹中的退出或中断。这是修复:

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:

无论你身在何处,更改

rescue Exception => e
  # ...
end

to

rescue StandardError => e
  # ...
end

对于那些你不能改变到StandardError,重新提出异常:

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

rescue Exception => e
  # ...
  raise
end

或至少重新提高SystemExit和中断

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

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

您所做的任何自定义异常应该衍生自 StandardError ,而不是异常

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

这篇关于以红宝石捕获Ctrl-c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆