1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The issue here is that your file is empty - which means that your for loop doesn't ever execute.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.