traceback.format_exc() will yield more info if that's what you want.

import traceback

def do_stuff():
    raise Exception("test exception")

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())

This outputs:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    do_stuff()
  File "main.py", line 5, in do_stuff
    raise Exception("test exception")
Exception: test exception
Answer from volting on Stack Overflow
Top answer
1 of 16
1523

traceback.format_exc() will yield more info if that's what you want.

import traceback

def do_stuff():
    raise Exception("test exception")

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())

This outputs:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    do_stuff()
  File "main.py", line 5, in do_stuff
    raise Exception("test exception")
Exception: test exception
2 of 16
879

Some other answer have already pointed out the traceback module.

Please notice that with print_exc, in some corner cases, you will not obtain what you would expect. In Python 2.x:

import traceback

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_exc()

...will display the traceback of the last exception:

Traceback (most recent call last):
  File "e.py", line 7, in <module>
    raise TypeError("Again !?!")
TypeError: Again !?!

If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info in a local variable and display it using print_exception:

import traceback
import sys

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        exc_info = sys.exc_info()

        # do you usefull stuff here
        # (potentially raising an exception)
        try:
            raise TypeError("Again !?!")
        except:
            pass
        # end of useful stuff


    finally:
        # Display the *original* exception
        traceback.print_exception(*exc_info)
        del exc_info

Producing:

Traceback (most recent call last):
  File "t.py", line 6, in <module>
    raise TypeError("Oups!")
TypeError: Oups!

Few pitfalls with this though:

  • From the doc of sys_info:

    Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)

  • but, from the same doc:

    Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.


On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:

import traceback

try:
    raise TypeError("Oups!")
except Exception as err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_tb(err.__traceback__)

... will display:

  File "e3.py", line 4, in <module>
    raise TypeError("Oups!")
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
The exception’s __str__() output is printed as the last part (‘detail’) of the message for unhandled exceptions.
Discussions

Print exception notes - in repr(exc) or otherwise - Ideas - Discussions on Python.org
Exception notes are printed in tracebacks, but they are omitted when an exception is handled and logged or printed. I think a possibly helpful information is lost. # Python 3.11+ enote = ValueError("error message") enot… More on discuss.python.org
🌐 discuss.python.org
0
September 4, 2024
python exception message capturing - Stack Overflow
Beware that except BaseException ... work in Python3, but it won't catch KeyboardInterrupt for instance (which can be very convenient if you want to be able to interrupt your code!), whereas BaseException catches any exception. See this link for the hierarchy of exceptions. 2018-06-18T21:52:36.5Z+00:00 ... If you want the error class, error message, and stack ... More on stackoverflow.com
🌐 stackoverflow.com
Try/Except isn't printing my message
Except is used for catching exceptions, but your code does not appear to throw any exceptions. I believe instead of the try and except, you want to use an else:. More on reddit.com
🌐 r/learnpython
8
August 18, 2023
Disable printing in unit tests
You could use redirect_stdout like this: from contextlib import redirect_stdout from io import StringIO import unittest import main class DivisionTests(unittest.TestCase): def test_zero_division(self): """Fails if the program doesn't exit when dividing by zero.""" with redirect_stdout(StringIO()) as stdout: with self.assertRaises(SystemExit) as e: main.divide(1, 0) self.assertEqual(stdout.getvalue(), 'Error: Cannot divide by zero.\n') self.assertEqual(e.exception.code, 1) More on reddit.com
🌐 r/learnpython
6
2
October 25, 2016
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-print-exception
Python Print Exception - GeeksforGeeks
July 23, 2025 - This method helps us print the type of exception you caught, like <class 'ValueError'>. It's useful when we're not sure what kind of error occurred. Along with type(e), we can also print e to get the actual error message.
🌐
freeCodeCamp
freecodecamp.org › news › python-print-exception-how-to-try-except-print-an-error
Python Print Exception – How to Try-Except-Print an Error
March 15, 2023 - For example, if you have a large ... try block and handle a possible error in the except block: try: print("Here's variable x:", x) except: print("An error occured") # An error occured...
🌐
Python.org
discuss.python.org › ideas
Print exception notes - in repr(exc) or otherwise - Ideas - Discussions on Python.org
September 4, 2024 - Exception notes are printed in tracebacks, but they are omitted when an exception is handled and logged or printed. I think a possibly helpful information is lost. # Python 3.11+ enote = ValueError("error message") enote.add_note("additional info") try: raise enote except Exception as exc: print(repr(exc)) # will NOT print 'additional info' Unless I overlooked something, the PEP 678 does not discuss the string representation, just the tracebacks.
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
Print one message if the try block raises a NameError and another for other errors: try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") Try it Yourself » · See more Error types in our Python Built-in Exceptions Reference.
Find elsewhere
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
1 month ago - The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file.
🌐
Honeybadger
honeybadger.io › blog › a-guide-to-exception-handling-in-python
The ultimate guide to Python exception handling - Honeybadger Developer Blog
March 28, 2025 - Instead of crashing, your code can log the error, show a user-friendly message, or even use some predetermined fallback logic. This makes exception handling essential for writing robust applications that can withstand a wide range of real-world scenarios. Here’s an example of a ZeroDivisionError exception being raised and handled using a try-except block: try: result = 10 / 0 # Raises ZeroDivisionError except ZeroDivisionError: print("Error: Division by zero!")
🌐
Coursera
coursera.org › tutorials › python-exception
How to Catch, Raise, and Print a Python Exception | Coursera
1 2 3 4 5 6 7 try: greeting = word1+word2 print(greeting) except TypeError: print("You can only concatenate strings to strings") except: print("Something else went wrong") ... Python attempts to execute the statements within the try clause first.
🌐
Tagline Infotech
taglineinfotech.com › home › how do i print an exception in python?
How do I Print an Exception in Python? - Tagline Infotech
December 31, 2025 - Master print an exception in Python with 'traceback' module. Customize messages for effective debugging.
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › python-try-except-print-error
How to print as exception in Python
July 31, 2023 - Traceback (most recent call last): ... ‘variable_that_does_not_exist’ is not defined The traceback.format_exc() function will print a detailed stack trace of the exception....
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
December 1, 2024 - Additionally, the error message gives you a hint about what went wrong. In this example, there was one bracket too many. Remove it and run your code again: ... >>> print(0 / 0) Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero · This time, you ran into an exception error. This type of error occurs whenever syntactically correct Python ...
🌐
Rollbar
rollbar.com › home › what is “except exception as e” in python?
What is “except Exception as e” in Python? | Rollbar
June 24, 2024 - try: # Code that might raise an exception result = 10 / 0 # Raises ZeroDivisionError except Exception as e: # Handles the exception print(f"An error occurred: {e}") ... The try block attempts to execute result = 10 / 0. Division by zero is not allowed so a ZeroDivisionError is raised. The except Exception as e block catches the ZeroDivisionError. The exception is assigned to the variable e, which contains the error message "division by zero".
🌐
Carmatec
carmatec.com › home › how to print and debug exceptions in python like a pro
How to Print and Debug Exceptions in Python Like a Pro
December 31, 2025 - Sometimes, you need more than just the error message—you need the full traceback to see where the error occurred. Python’s traceback module is perfect for this. python import traceback try: result = 10 / 0 except ZeroDivisionError: traceback.print_exc()
🌐
Finxter
blog.finxter.com › home › learn python blog › how to print exception messages in python (try-except)
How to Print Exception Messages in Python (Try-Except) - Be on the Right Side of Change
October 30, 2023 - The error message is printed, but ... a single line of code in Python involves utilizing string formatting within the print() function to display a succinct and clear error message....
🌐
Medium
taglineinfotechus.medium.com › how-do-i-print-an-exception-in-python-e680ec4e2b39
How do I Print an Exception in Python? | by Tagline Infotech LLP | Medium
November 24, 2023 - To print exceptions, we can use the except clause along with the print statement. try: # Your code that might raise an exception except Exception as e: print(f"An exception occurred: {e}") By tailoring messages ...
🌐
Server Academy
serveracademy.com › blog › python-try-except
Python Try Except - Server Academy
In Python, try and except are used to catch and handle exceptions, allowing your program to continue executing or provide custom error messages rather than crashing. Here’s a basic syntax for using try and except: try: # Code that might raise an exception except SomeException: # Code to run if the exception occurs · Let’s look at a simple example to handle division by zero: try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")
🌐
Embedded Inventor
embeddedinventor.com › home › print just the message of an exception
Print just the message of an exception
September 27, 2023 - One way to print the message is by catching the exception using a try-except block and storing it as an exception object, and then simply print it. This method is pretty simple and short, have a look.