What’s the correct way to print an exception in Python when handling errors?

I’m a bit confused about the proper way to display errors when using a try/except block in Python. I’m catching exceptions successfully, but I’m not sure how to actually print the exception in a meaningful way.

Right now, my except block runs, but I don’t know how to access or display the error details correctly. I’ve seen a few examples online, but they’re not very clear on what’s considered best practice for a simple python print exception use case.

try:
    perform_action()
except Exception as err:
    print(err)  # Is this the right way to print the exception?

Is this the recommended approach to print the error message, or is there a better/cleaner way to output the exception information from inside the except block?

Any clarification or examples would be really helpful. Thanks!

Hey, I’ve run into this exact situation a lot while testing small scripts. If all you want is to quickly see what went wrong, simply printing the exception works fine. For example:

try:
    perform_action()
except Exception as err:
    print("Oops, something went wrong:", err)

This shows the error message immediately, like ValueError: Invalid input, and your program keeps running. I use this method all the time when I’m experimenting or debugging a single function. It’s super simple and doesn’t require any extra setup. The only thing to remember is that you won’t see the line number or the full stack trace, so it’s mostly good for quick debugging rather than tracking complicated issues.

From my experience working on slightly bigger scripts, I realized that just printing the error message often isn’t enough. Sometimes the exception comes from deeper in a call stack, and without context, it’s hard to figure out what went wrong. That’s when I started using the traceback module:

import traceback

try:
    perform_action()
except Exception as err:
    print("Caught an exception, full details below:")
    traceback.print_exc()

This prints the full stack trace while keeping the program running. It’s incredibly helpful for debugging multi-function scripts or loops where errors can pop up in different places. Personally, this has saved me a ton of time tracking down where an error originated.

When I moved to larger projects or scripts that run regularly in production, I realized just printing the exception isn’t sustainable. That’s when I started using the logging module with exc_info=True:

import logging

logging.basicConfig(level=logging.ERROR)

try:
    perform_action()
except Exception as err:
    logging.error("Something went wrong!", exc_info=True)

This approach not only prints the full stack trace but also stores it in your logs. It’s super handy for scripts that run unattended or when you need to debug issues after the fact. I personally prefer this method for anything beyond small experiments, because it’s clean, professional, and makes debugging much easier.