Ruby Timeout在2.0和2.1之间表现不同

时间:2016-02-17 03:16:51

标签: ruby ruby-2.0 ruby-2.1

以下代码在ruby 2.0和2.1之间的行为有所不同:

require 'timeout'

def scp
  begin
    puts "In begin"
    sleep 10
  rescue Exception => e
    puts "Exception found: #{e}"
  else
    puts "No exception found"
  ensure
    puts "In ensure"
  end
end

Timeout::timeout(1) do
  scp
end

在ruby 2.0中,它给出了:

In begin
Exception found: execution expired
In ensure

在ruby 2.1中,它给出了:

In begin
In ensure
t2.rb:7:in `sleep': execution expired (Timeout::Error)
    from t2.rb:7:in `scp'
    from t2.rb:18:in `block in <main>'
    from /usr/local/rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/timeout.rb:91:in `block in timeout'
    from /usr/local/rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/timeout.rb:35:in `block in catch'
    from /usr/local/rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/timeout.rb:35:in `catch'
    from /usr/local/rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/timeout.rb:35:in `catch'
    from /usr/local/rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/timeout.rb:106:in `timeout'
    from t2.rb:17:in `<main>'

为什么他们不同?

1 个答案:

答案 0 :(得分:4)

这是记录在案的行为。我们可以比较用于2.0.02.1.0的Ruby的Timeout模块的文档。 2.1.0的文档说:

  

除非明确给出klass,否则无法在块内部获取终止给定块的异常。

如果您想在应用程序中使用旧行为,可以致电Timeout::timeout(1, Timeout::Error)。这将允许您捕获定时块内的异常。