Reputation:
I am having difficulties with raising exceptions, for example:
import csv
o = open('/home/foo/dummy.csv', 'r') # Empty file!
reader = csv.reader(o, delimiter=';')
reader = list(reader)
try:
for line in reader:
print line[999] # Should raise index out of range!
except Exception, e:
print e
Basically csv.reader reads empty file, is converted to an empty list, and code above should print IndexError. But it does not. Code below however raises perfectly:
print reader[0][999]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Am I doing something wrong?
Upvotes: 1
Views: 148
Reputation: 771
The issue here is that your file is empty - which means that your for loop doesn't ever execute.
Upvotes: 0
Reputation: 213243
Well, since reader is an empty list, so your for
loop is never executed. So, line[999]
is not executed. That is why no exception is thrown.
As for the other code, the exception is thrown because you accessed the 0th
index of the empty list. Try just to access reader[0]
and see whether you get an exception or not.
Upvotes: 2