Reputation: 271534
How do I print the error/exception in the except:
block?
try:
...
except:
print(exception)
Upvotes: 1488
Views: 2205801
Reputation: 1121
(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)
I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:
except Exception as e:
print(e)
will print the error output to sys.stdout
by default. A more appropriate approach to error handling in general would be:
except Exception as e:
print(e, file=sys.stderr)
(Note that you have to import sys
for this to work.) This way, the error is printed to STDERR
instead of STDOUT
, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.
I haven't used the traceback
module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.
Upvotes: 86
Reputation: 14707
logging
Instead of using the basic print()
function, the more flexible logging
module can be used to log the exception. The logging
module offers a lot extra functionality, for example, logging messages...
For more information check out the official documentation.
Logging an exception can be done with the module-level function logging.exception()
like so:
import logging
try:
1/0
except BaseException:
logging.exception("An exception was thrown!")
ERROR:root:An exception was thrown!
Traceback (most recent call last):
File ".../Desktop/test.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
the function logging.exception()
should only be called from an exception handler
the logging
module should not be used inside a logging handler to avoid a RecursionError
(thanks @PrakharPandey)
It's also possible to log the exception with another log level but still show the exception details by using the keyword argument exc_info=True
, like so:
logging.critical("An exception was thrown!", exc_info=True)
logging.error ("An exception was thrown!", exc_info=True)
logging.warning ("An exception was thrown!", exc_info=True)
logging.info ("An exception was thrown!", exc_info=True)
logging.debug ("An exception was thrown!", exc_info=True)
# or the general form
logging.log(level, "An exception was thrown!", exc_info=True)
Of course, if you don't want the whole traceback but only some specific information (e.g., exception name and description), you can still use the logging
module like so:
try:
1/0
except BaseException as exception:
logging.warning(f"Exception Name: {type(exception).__name__}")
logging.warning(f"Exception Desc: {exception}")
WARNING:root:Exception Name: ZeroDivisionError
WARNING:root:Exception Desc: division by zero
Upvotes: 143
Reputation: 1271
Expanding off of the "except Exception as e:" solution here is a nice one liner which includes some additional info like the type of error and where it occurred.
try:
1/0
except Exception as e:
print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}")
Output:
ZeroDivisionError at line 48 of /Users/.../script.py: division by zero
Upvotes: 91
Reputation: 575
Try this
try:
print("Hare Krishna!")
except Exception as er:
print(er)
Upvotes: 40
Reputation: 184
I would recommend using a try-except statement. Also, rather than using a print statement, a logging exception logs a message with level ERROR on the logger, which I find is more effective than a print output. This method should only be called from an exception handler, as it is here:
import logging
try:
*code goes here*
except BaseException:
logging.exception("*Error goes here*")
There's good documentation on this python page if you want to learn more about logging and debugging.
Upvotes: 6
Reputation: 1000
One has pretty much control on which information from the traceback to be displayed/logged when catching exceptions.
The code
with open("not_existing_file.txt", 'r') as text:
pass
would produce the following traceback:
Traceback (most recent call last):
File "exception_checks.py", line 19, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
As others already mentioned, you can catch the whole traceback by using the traceback module:
import traceback
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
traceback.print_exc()
This will produce the following output:
Traceback (most recent call last):
File "exception_checks.py", line 19, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
You can achieve the same by using logging:
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
logger.error(exception, exc_info=True)
Output:
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
File "exception_checks.py", line 27, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
You might not be interested in the whole traceback, but only in the most important information, such as Exception name and Exception message, use:
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
print("Exception: {}".format(type(exception).__name__))
print("Exception message: {}".format(exception))
Output:
Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'
Upvotes: 70
Reputation: 129744
The traceback
module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:
import traceback
try:
1/0
except Exception:
traceback.print_exc()
Output:
Traceback (most recent call last):
File "C:\scripts\divide_by_zero.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
Upvotes: 818
Reputation: 96716
For Python 2.6 and later and Python 3.x:
except Exception as e: print(e)
For Python 2.5 and earlier, use:
except Exception,e: print str(e)
Upvotes: 1996
Reputation: 5470
One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.
assert type(A) is type(""), "requires a string"
Upvotes: 4
Reputation: 18816
In Python 2.6 or greater it's a bit cleaner:
except Exception as e: print(e)
In older versions it's still quite readable:
except Exception, e: print e
Upvotes: 202
Reputation: 43110
In case you want to pass error strings, here is an example from Errors and Exceptions (Python 2.6)
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
Upvotes: 73