46

有没有办法Exception在 Python 的 try-except 块中使用对象的属性/属性?

例如,在 Java 中,我们有:

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

Python中的什么等价物会给我一个参考e

4

3 回答 3

80

使用as语句。您可以在处理异常中阅读更多相关信息。

>>> 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']
于 2012-09-23T17:05:44.790 回答
9

这是文档中的一个示例:

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
于 2012-09-23T17:06:45.300 回答
8

当然,有:

try:
    # some code
except Exception as e:
    # Here we can use some the attribute of "e"
于 2012-09-23T17:06:06.313 回答