---
title: "How do I print an exception in Python?"  
description: "How do I print an exception in Python?"  
author: "Revati S Misra"  
published: 2023-07-20  
updated: 2023-07-20  
canonical: https://www.mindstick.com/forum/159181/how-do-i-print-an-exception-in-python  
category: "python"  
tags: ["exception handling", "exception", "python"]  
reading_time: 2 minutes  

---

# How do I print an exception in Python?

How do I [print](https://www.mindstick.com/blog/301752/types-of-3d-printing-technology) an [exception](https://www.mindstick.com/articles/1824/objective-c-exception-handling) in [Python](https://www.mindstick.com/articles/75378/simple-yet-useful-tips-when-using-python)?

## Replies

### Reply by Aryan Kumar

Sure, here are the steps on how to print an exception in Python:

1. Use a try-except block. The try-except block is a way to handle exceptions in Python. The try block contains the code that you are trying to run, and the except block contains the code that you want to run if an exception is raised.

```plaintext
try:
  # This code might raise an exception
  1 / 0
except Exception as e:
  # Print the exception
  print(e)
```

1. Use the `print_exception()` function. The `print_exception()` function is a built-in function in Python that prints the exception information to the console.

```plaintext
import traceback

try:
  # This code might raise an exception
  1 / 0
except Exception as e:
  # Print the exception information to the console
  traceback.print_exception(e)
```

1. Use the `logging` module. The `logging` module is a Python module that provides a way to log messages to a file or console. You can use the `logging.exception()` function to log an exception to a file or console.

```plaintext
import logging

try:
  # This code might raise an exception
  1 / 0
except Exception as e:
  # Log the exception to a file
  logging.exception("An exception occurred: %s", e)
```

Here are some additional tips for printing an exception in Python:

- You can use the `type()` function to get the type of the exception.
- You can use the `__str__()` method to get the string representation of the exception.
- You can use the `traceback` module to get the stack trace of the exception.
- You can use the `logging` module to log the exception to a file or console.


---

Original Source: https://www.mindstick.com/forum/159181/how-do-i-print-an-exception-in-python

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
