2013-07-18 48 views
1

對於目錄中的每個文件,我需要對它做些什麼,然後將結果寫入另一個文件。如果發生超時異常,請繼續進行下一次循環迭代。for循環中的捕捉超時異常

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 

從外殼程序運行錯誤是:

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

任何想法,我怎麼能糾正呢?

回答

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 
+1

呃,好吧,downvoting可以是非常有用的,也就是說,刪除chafe /冗餘帖子。可能最好是所有這些外交:-) – Renklauf

+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