Zaid Khan
Zaid Khan

Reputation: 263

usage of except and store error in a variable

I need to catch all the errors,exceptions, and everything that stops the execution of a code and store it in a variable. I want something like this:

try:
    Error generating code
except as err:
    print err

But this doesnt work. Is there any other way to do the same?

Upvotes: 13

Views: 16411

Answers (1)

janos
janos

Reputation: 124646

except as err: doesn't work because the correct syntax is:

except TypeOfError as somename:

To catch any type of error, use Exception as the type, it is the common base class for all non-exit exceptions in Python:

try:
    # Error generating code
except Exception as err:
    print(err)

err will be an instance of the actual exception that was raised, you can see its correct type with type(err), and it's attributes and methods with dir(err).

Keep in mind that it's recommended to use the most specific type of exception that may be raised.

See more details in Python's tutorial on error handling.

Upvotes: 20

Related Questions