如何在Python中使用异常的属性?

2024-04-20 06:41:10 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python的try-except块中,是否有方法使用Exception对象的属性/属性?

例如,在Java中,我们有:

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

Python中的哪个等价项会给我一个对e的引用?


Tags: of对象方法属性hereuseexceptioncode
3条回答

当然,有:

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

使用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']

下面是来自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

相关问题 更多 >