1

I have this Ruby script to convert my Word-documents to .txt format. It works fine and can convert multiple files after each other but now and then there is an error. How do i let the script continue with the next file, skipping the file that gave the error ? Please no suggestions about using other techniques, i'm happy with this one.

require 'win32ole'

wdFormatDOSText = 4

word = WIN32OLE.new('Word.Application')
word.visible = false

begin
  ARGV.each do|file|
    myFile = word.documents.open(file)
    new_file = file.rpartition('.').first + ".txt"
    word.ActiveDocument.SaveAs new_file, wdFormatDOSText
    puts new_file
    word.activedocument.close(false) # no save dialog, just close it
  end
rescue WIN32OLERuntimeError => e
  puts e.message
  puts e.backtrace.inspect
  sleep 30
ensure
  word.quit
end
sleep 3
4

1 に答える 1

1

When iterating over a collection you can start a new begin...rescue...end block at the start of each iteration and call next within the rescue block:

[ "puts 'hello'", "raise '!'" , "puts 'world'" ].each do |str|
  begin
    eval str
  rescue
    puts "caught an error, moving on"
    next
  end
end

# => hello
# => caught an error, moving on
# => world

So in your case it could look something like this:

ARGV.each do |file|
  begin
    # ...
  rescue WIN32OLERuntimeError => e
    puts e.message
    next
  end
end
于 2012-11-10T01:15:52.040 に答える