内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
begin #dosomething rescue Exception => e #halt the exception's progress end
我希望能够使用Ctrl+C关闭它。
我想要写的代码是:
begin #dosomething rescue SignalException => e raise e rescue Exception => e #halt the exception's progress end
当一个Ruby程序结束时,它通过引发SystemExit来完成。当一个ctrl+C进来时,会引发中断。
rescue Exception => e
# ...
end
rescue StandardError => e
# ...
end
rescue Exception => e
# ...
raise
end
rescue SystemExit, Interrupt
raise
rescue Exception => e
#...
end
任何自定义异常都应该来自StandardError,而不是Exception。
如果可以打包整个程序,执行如下操作:
trap("SIGINT") { throw :ctrl_c } catch :ctrl_c do begin sleep(10) rescue Exception puts "Not printed" end end
这基本上是CtrlC使用CATCH/HOP而不是异常处理,所以除非现有代码已经有了CATCH:Ctrl_C在里面。