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?
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.
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