2011-03-03 18 views
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' 

但是第二個版本 - 具有更多信息錯誤描述的版本 - 在默默地失敗。爲什麼是這樣?

+1

我能想到這可能發生的唯一方法就是在某個外部範圍內捕獲'RuntimeError'。 – 2011-03-03 15:47:19

+0

試着提高'KeyError'而不是'RuntimeError' – NullUserException 2011-03-03 15:53:16

+0

@Sven +1。你可以用'raise KeyError('來代替'raise RuntimeError('並且看看會發生什麼。 – jammon 2011-03-03 15:55:28

回答

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,可能的解釋是。