【问题标题】:Try/Except in a loop循环尝试/排除
【发布时间】:2013-06-20 11:40:18
【问题描述】:

我在提出异常时遇到困难,例如:

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

基本上 csv.reader 读取空文件,转换为空列表,上面的代码应该打印 IndexError。但事实并非如此。 然而,下面的代码完美地提出了:

print reader[0][999]

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

我是不是做错了什么?

【问题讨论】:

    标签: python exception python-2.7 exception-handling


    【解决方案1】:

    好吧,因为 reader 是一个空列表,所以你的 for 循环永远不会执行。所以,line[999] 没有被执行。这就是为什么没有抛出异常。

    至于其他代码,由于您访问了空列表的0th 索引,因此引发了异常。尝试访问reader[0],看看是否有异常。

    【讨论】:

      【解决方案2】:

      这里的问题是您的文件是空的 - 这意味着您的 for 循环永远不会执行。

      【讨论】:

        猜你喜欢
        • 2021-04-08
        • 2016-01-19
        • 2014-05-09
        • 1970-01-01
        • 2019-03-17
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多