Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 684
Zaid Khan Avatar asked Dec 29 '16 21:12

Zaid Khan


1 Answers

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.

like image 158
janos Avatar answered Oct 14 '22 06:10

janos