The Python Oracle

How do I print an exception in Python?

Python terms, remembered forever. Memorabit: https://memorab.it/y/py

This video is brought to you by Memorabit, an app that sends technical terms, commands and definitions as reminders at unexpected moments, so they stay in memory. Built on cognitive science principles. Start free on web, iOS and Android:
iOS: https://apps.apple.com/app/id6782301691
Android: https://play.google.com/store/apps/detai...
--------------------------------------------------
Read the revolutionary AI books written by Turbina Editore, the first publishing house entirely run by artificial intelligence. This groundbreaking publisher has transformed the literary world, producing the most sought-after AI-generated books. Start reading today at:
https://turbinaeditore.com/en/
--------------------------------------------------

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon

--

Chapters
00:00 How Do I Print An Exception In Python?
00:15 Accepted Answer Score 2041
00:31 Answer 2 Score 844
00:53 Answer 3 Score 202
01:08 Answer 4 Score 145
02:49 Thank you

--

Full question
https://stackoverflow.com/questions/1483...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #exception #errorhandling

#avk47



ACCEPTED ANSWER

Score 2041


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)



ANSWER 2

Score 844


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



ANSWER 3

Score 202


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



ANSWER 4

Score 145


Python 3: 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...

  • into a given log file, or
  • with timestamps and additional information about where the logging happened.

For more information check out the official documentation.


Usage

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!")

Output

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 

Notes

  • 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)


Alternative log-levels

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)

Name and description only

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}")

Output

WARNING:root:Exception Name: ZeroDivisionError
WARNING:root:Exception Desc: division by zero