在for循环中捕获超时异常

时间:2013-07-18 18:20:05

标签: ruby exception

对于目录中的每个文件,我需要对其执行某些操作,然后将结果写入另一个文件。如果引发超时异常,请继续循环的下一次迭代。

 require 'timeout'
 timeout_in_seconds = 60

 for fl in Dir.glob('/dir/files')
     begin 
     Timeout::timeout(timeout_in_seconds) do 
 #do something here to get $results
 File.open('new_file', 'w') { |file| file.write(results) }
     end
     rescue Timeout::Error
 next
 end

从shell运行错误是:

  syntax error, 'unexpected kRESCUE, expecting kEND
rescue Timeout::Error

关于我如何纠正这个问题的任何想法?

2 个答案:

答案 0 :(得分:1)

rescue应该在结束条款之前。

require 'timeout'
timeout_in_seconds = 60

for fl in Dir.glob('/dir/files')
  begin 
    Timeout::timeout(timeout_in_seconds) do 
    #do something here to get $results
    File.open('new_file', 'w') { |file| file.write(results) }
  rescue Timeout::Error

  end
end

答案 1 :(得分:0)

您在上面的代码中遗漏了两个end。写下面的内容。

require 'timeout'
timeout_in_seconds = 60

 for fl in Dir.glob('/dir/files')
     begin 
     Timeout::timeout(timeout_in_seconds) do 
       #do something here to get $results
       File.open('new_file', 'w') { |file| file.write(results) }
     end
     rescue Timeout::Error
      next # although I am not sure why this is needed.
     end
 end