Python没有正确捕获KeyError

时间:2011-03-03 15:44:21

标签: python

我尝试了同一个功能的两个不同版本:

def position_of(self, table_name, column_name):
    positions = self.heading_positions()
    position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
    return position

-

def position_of(self, table_name, column_name):
    positions = self.heading_positions()
    try:
        position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
    except KeyError:
        raise RuntimeError('No heading found for {t}.{c} in import profile "{ip}"'.format(t=table_name, c=column_name, ip=self))
    return position

对于第一个版本,我收到以下错误,这很好:

Traceback (most recent call last):
  File "./import.py", line 15, in <module>
    g.process()
  File "/home/jason/projects/mcifdjango/mcif/models/generic_import.py", line 39, in process
    row.process()
  File "/home/jason/projects/mcifdjango/mcif/models/csv_row.py", line 18, in process
    self.save()
  File "/home/jason/projects/mcifdjango/mcif/models/csv_row.py", line 26, in save
    self.output("Phone: " + self.value('customer', 'phone'));
  File "/home/jason/projects/mcifdjango/mcif/models/csv_row.py", line 60, in value
    print self.generic_import.import_profile.position_of(table_name, column_name)
  File "/home/jason/projects/mcifdjango/mcif/models/import_profile.py", line 22, in position_of
    position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
KeyError: 'customer.phone'

但第二个版本 - 具有更多信息性错误描述的版本 - 无声地失败。这是为什么?

1 个答案:

答案 0 :(得分:2)

position_of的第二个版本适用于我。我把它变成了一个最小的完整程序如下:

class Test(object):

    def heading_positions(self):
        return {}

    def position_of(self, table_name, column_name):
        positions = self.heading_positions()
        try:
            position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
        except KeyError:
            raise RuntimeError('No heading found for {t}.{c} in import profile "{ip}"'.format(t=table_name, c=column_name, ip=self))
        return position

a = Test()
a.position_of('customer', 'phone')

当我运行它(在MacOS X上使用Python 2.6.6)时,我收到以下错误消息:

Traceback (most recent call last):
  File "./a.py", line 17, in <module>
    a.position_of('customer', 'phone')
  File "./a.py", line 13, in position_of
    raise RuntimeError('No heading found for {t}.{c} in import profile "{ip}"'.format(t=table_name, c=column_name, ip=self))
RuntimeError: No heading found for customer.phone in import profile "<__main__.Test object at 0x100426ad0>"

这表明抓住KeyError并将其转换为RuntimeError可以正常工作。这个例子适合你吗?正如Sven已经写过的那样,如果你在调用链的某个地方捕获RuntimeError而不是KeyError,可能会有一个解释。