Python
Exception Handling
Debugging
Programming
Print Statement

How do I print an exception in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Printing an exception in Python can mean three slightly different things: printing only the error message, printing the exception type and message, or printing the full traceback. The right choice depends on whether you are debugging locally, writing user-facing messages, or logging failures in production code.

If you only want the message, catch the exception and print the exception object:

python
1try:
2    10 / 0
3except Exception as exc:
4    print(exc)

That prints the exception's string form. For a ZeroDivisionError, the output is the familiar message about division by zero.

This is useful for quick debugging, but it does not show where the error happened.

If you want a little more context:

python
1try:
2    int("abc")
3except Exception as exc:
4    print(type(exc).__name__)
5    print(exc)

This shows both the exception class and the message, which is often enough for simple command-line tools.

For real debugging, use the traceback module:

python
1import traceback
2
3try:
4    values = [1, 2]
5    print(values[5])
6except Exception:
7    traceback.print_exc()

This prints:

  • the traceback
  • the file and line number
  • the exception type
  • the message

That is usually what you want when diagnosing a real failure.

Use Logging in Application Code

In longer-running applications, logging is usually better than raw print:

python
1import logging
2
3logging.basicConfig(level=logging.ERROR)
4
5try:
6    {}["missing"]
7except Exception:
8    logging.exception("Request failed")

logging.exception automatically includes the traceback when called inside an except block. This is one of the cleanest production-friendly ways to record an exception.

If you need the traceback text instead of printing it immediately, traceback.format_exc() returns the formatted traceback as a string. That is useful for tests, custom log payloads, or error reports sent elsewhere.

It is also handy when you need to include exception details in a larger multi-line diagnostic message instead of sending output directly to stderr. That makes it easier to attach the failure to JSON logs or test reports.

Re-Raise After Printing if Needed

Sometimes you want to print or log the exception but still let the caller handle it:

python
1import traceback
2
3def load_data():
4    try:
5        raise ValueError("bad data")
6    except Exception:
7        traceback.print_exc()
8        raise

The raise statement re-throws the current exception so the failure is not silently swallowed.

That matters because printing an exception is not the same thing as handling it correctly.

What Not to Do

Avoid a bare except: unless you have a very specific reason. It catches more than ordinary application errors, including exceptions you may not want to suppress.

Also avoid printing an exception and then continuing as if nothing happened unless that is a conscious recovery strategy. Hidden failures are harder to debug than noisy failures.

Common Pitfalls

The biggest mistake is printing only exc when you really need the traceback. The message alone often is not enough to find the bug.

Another mistake is catching Exception, printing it, and then swallowing it silently. That turns a failure into strange downstream behavior.

A third issue is using print in code that should use structured logging. Debug scripts can get away with prints; services and applications usually should not.

Summary

  • Use print(exc) when you only need the exception message.
  • Use type(exc).__name__ if you also want the exception class.
  • Use traceback.print_exc() for full debugging context.
  • Use logging.exception(...) in real application code.
  • Print or log exceptions intentionally, and re-raise them when the failure should still propagate.

Course illustration
Course illustration

All Rights Reserved.