How to use an Exception's attributes in Python?
Question:
Is there a way to use the attributes/properties of an Exception
object in a try-except block in Python?
For example in Java we have:
try {
// Some code
} catch(Exception e) {
// Here we can use some of the attributes of "e"
}
What equivalent in Python would give me a reference to e
?
Answers:
Use the as
statement. You can read more about this in 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']
Sure, there is:
try:
# some code
except Exception as e:
# Here we can use some the attribute of "e"
Here is an example from the 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
Is there a way to use the attributes/properties of an Exception
object in a try-except block in Python?
For example in Java we have:
try {
// Some code
} catch(Exception e) {
// Here we can use some of the attributes of "e"
}
What equivalent in Python would give me a reference to e
?
Use the as
statement. You can read more about this in 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']
Sure, there is:
try:
# some code
except Exception as e:
# Here we can use some the attribute of "e"
Here is an example from the 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