2
我試過兩個不同的版本相同的功能:Python是不要再追KeyError異常正確
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'
但是第二個版本 - 具有更多信息錯誤描述的版本 - 在默默地失敗。爲什麼是這樣?
我能想到這可能發生的唯一方法就是在某個外部範圍內捕獲'RuntimeError'。 – 2011-03-03 15:47:19
試着提高'KeyError'而不是'RuntimeError' – NullUserException 2011-03-03 15:53:16
@Sven +1。你可以用'raise KeyError('來代替'raise RuntimeError('並且看看會發生什麼。 – jammon 2011-03-03 15:55:28