Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an Exception's attributes in Python?

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?

like image 352
Kozet Avatar asked Sep 23 '12 17:09

Kozet


People also ask

What are the attributes of exception in Python?

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.

How do you use exceptions in Python?

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.

What are the 3 types of errors in Python?

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.

How is try block used in Python?

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.


1 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'] 
like image 186
Ashwini Chaudhary Avatar answered Sep 26 '22 05:09

Ashwini Chaudhary