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
?
A tuple of the argument values provided when the exception was created. Generally this is the error message associated with the exception. However, an exception can be created with a collection of values instead of a message string; these are collected into the args attribute.
In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.
There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.
The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With