Coding⏱️ 2 min read📅 2026-05-30

How to Fix: How do I print an exception in Python

Learn how to print exceptions in Python with the exception object.

Quick Answer: Use `print(exception)` within the `except` block to display the error message.

In Python, when an exception occurs, it is not possible to directly print the `exception` variable in the `except:` block. This is because `exception` is a reserved keyword and cannot be used as a variable name.

⚠️ Common Causes

  • Using `except:` without specifying the exception type.

🔧 Proven Troubleshooting Steps

Method 1: Catching Specific Exceptions

  1. Step 1: Use the `except` keyword followed by the specific exception type, e.g., `except TypeError:`.

Method 2: Wrapping with a Generic Exception

  1. Step 1: Use the `except` keyword followed by a generic exception type, e.g., `except Exception:`.

✨ Wrapping Up

To print the exception in Python, you can use the `str()` function to convert it to a string and then print it. For example: `print(str(e))` where `e` is the exception object.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions