2012-09-23 18 views
12

有沒有辦法在Python的try-except塊中使用異常對象的屬性/屬性?如何在Python中使用異常的屬性?

例如在Java中,我們有:

try{ 
    // Some Code 
}catch(Exception e){ 
    // Here we can use some of the attributes of "e" 
} 

在Python相當於什麼會給我爲 'E' 的參考?

+17

爲什麼收盤票?這是一個非常合理的問題。 –

+0

我同意。這個問題很古怪。這幾乎就像「我如何編寫Python」? – Aaron

+0

我也不明白「不是真正的問題」。問題非常具體,Ashwini Chaudhary給出了一個很好的答案。 –

回答

34

使用as聲明。您可以在Handling Exceptions中閱讀更多關於此的信息。

>>> try: 
...  print(a) 
... except NameError as e: 
...  print(dir(e)) # print attributes of e 
... 
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', 
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
'__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__traceback__', 'args', 
'with_traceback'] 
6

當然,也有:

try: 
    # some code 
except Exception as e: 
    # Here we can use some the attribute of "e" 
7

下面是來自docs一個例子:

class MyError(Exception): 
    def __init__(self, value): 
     self.value = value 

    def __str__(self): 
     return repr(self.value) 

try: 
    raise MyError(2*2) 
except MyError as e: 
    print 'My exception occurred, value:', e.value 
相關問題