2012-09-23 6 views
12

Pythonのtry-exceptブロックで例外オブジェクトの属性/プロパティを使用する方法はありますか? Javaで例えばPythonで例外の属性を使用するには?

我々はしている:Pythonで

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

何同等は私に '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 
関連する問題