tags:

views:

53

answers:

3

Greetings,

I've a ruby script thats opening files and inserting the data inside the file into a database. Some of the files are missing so when the script attempts to open the file it throws a file not found exception.

Can anyone tell me how I can continue the process instead of the whole thing coming to an abrupt end. Please note this is the first thing I've ever done with ruby so be gentle! :-)

The code I'm using is as follows

def insertData
for i in (1..93)
puts "now looking at #{i}"
file = File.new("callspan/#{i}", "r")  
while(line = file.gets)
with_db do |db|
db.query(line)
end
end
end
+3  A: 

Either wrap the opening of the file with a call to File.exists?, or rescue from the exception. I prefer the former, if you expect it to be a common case (exceptions are for "exceptional" problems).

def insertData
  for i in (1..93)
    puts "now looking at #{i}"
    next if !File.exists?("callspan/#{1}")
    file = File.new("callspan/#{i}", "r")  
    while(line = file.gets)
      with_db do |db|
        db.query(line)
      end
    end
  end
end
Adam Wright
+1  A: 

Simple one line exception handling:

10 / 0 rescue nil

Rescue only file not found exceptions:

def insert_data
  (1..93).each do |i|
    puts "now looking at #{i}"
    begin
      file = File.new("callspan/#{i}", 'r')
      while(line = file.gets)
        with_db do |db|
          db.query(line)
        end
      end
    rescue Errno::ENOENT
      puts "skipping #{i}"
    end
  end
end
yawn
where do I stick that?
steve
See the answer of Leonid Shevtsov. If you only want to catch the file not found exception rescue Errno::ENOENT.
yawn
A: 

Use rescue nil to catch exceptions, like this:

def insertData
  for i in (1..93)
    puts "now looking at #{i}"
    File.open("callspan/#{i}", "r").each_line do |line|
      with_db do |db|
        db.query(line)
      end
    end rescue nil
  end
end

(i'd also put with_db around the cycle, it's probably more efficient)

Leonid Shevtsov