ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/ |
| Last Crawled | 2026-04-10 07:51:30 (14 hours ago) |
| First Indexed | 2020-11-23 11:50:32 (5 years ago) |
| HTTP Status Code | 200 |
| Meta Title | How to Print Exception Messages in Python (Try-Except) - Be on the Right Side of Change |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | Python comes with extensive support for exceptions and exception handling. An exception event interrupts and, if uncaught, immediately terminates a running program. The most popular examples are the
IndexError
,
ValueError
, and
TypeError
.
An exception will immediately terminate your program. To avoid this, you can
catch the exception
with a
try/except
block around the code where you expect that a certain exception may occur. Here’s how you
catch and print a given exception:
To catch and print an exception that occurred in a code snippet, wrap it in an indented
try
block, followed by the command
"except Exception as e"
that catches the exception and saves its error message in string variable
e
. You can now print the error message with
"print(e)"
or use it for further processing.
try:
# ... YOUR CODE HERE ... #
except Exception as e:
# ... PRINT THE ERROR MESSAGE ... #
print(e)
Next, I’ll guide you through 13 hand-picked examples for specific scenarios such as with or without traceback. Exception printing is more powerful than you’d think! Let’s get started! 👇
Example 1: Catch and Print IndexError
If you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an
IndexError
telling you that the list
index is out of range
.
try:
lst = ['Alice', 'Bob', 'Carl']
print(lst[3])
except Exception as e:
print(e)
print('Am I executed?')
Your genius code attempts to access the fourth element in your list with index 3—that doesn’t exist!
Fortunately, you wrapped the code in a
try/catch
block and printed the exception. The program is not terminated. Thus, it executes the final
print()
statement after the exception has been caught and handled. This is the output of the previous code snippet.
list index out of range
Am I executed?
🌍
Recommended Tutorial:
How to Print an Error in Python?
Example 2: Catch and Print ValueError
The
ValueError
arises if you try to use wrong values in some functions. Here’s an example where the
ValueError
is raised because you tried to calculate the square root of a negative number:
import math
try:
a = math.sqrt(-2)
except Exception as e:
print(e)
print('Am I executed?')
The output shows that not only the error message but also the string
'Am I executed?'
is printed.
math domain error
Am I executed?
Example 3: Catch and Print TypeError
Python throws the
TypeError
object is not subscriptable
if you use indexing with the square bracket notation on an object that is not indexable. This is the case if the object doesn’t define the
__getitem__()
method. Here’s how you can catch the error and print it to your shell:
try:
variable = None
print(variable[0])
except Exception as e:
print(e)
print('Am I executed?')
The output shows that not only the error message but also the string
'Am I executed?'
is printed.
'NoneType' object is not subscriptable
Am I executed?
I hope you’re now able to catch and print your error messages.
Example 4: Python Print Exception Message with str()
Use a
try/except
block, the code attempts to execute a statement and, if an exception arises, it captures and displays the corresponding error message using Python’s built-in
str()
function, aiding in the identification and resolution of issues.
try:
x = undefined_variable
except Exception as e:
print(str(e))
In this code, we reference an undefined variable, which will raise a
NameError
. The error message is then printed. Note that this is semantically equivalent to
print(e)
which internally calls
str(e)
to find a string representation of
e
.
Output
:
name 'undefined_variable' is not defined
Example 5: Python Print Exception Traceback
By using the
traceback
module, you can retrieve and print the entire traceback of an exception, offering a comprehensive view of where the error occurred and the call stack that led to it.
import traceback
try:
open("nonexistent_file.txt")
except Exception:
print(traceback.format_exc())
Here, we attempt to open a non-existent file, which will raise a
FileNotFoundError
. The traceback is printed, providing detailed error information.
Output
:
Traceback (most recent call last):
...
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'
Example 6: Python Print Exception Stack Trace
Printing the stack trace in Python involves using the
traceback
module to display the path taken by the code up to the point where the exception was raised. This method is particularly useful for understanding the sequence of function calls that led to the error, providing a clear view of the execution flow and aiding developers in pinpointing the origin of issues.
import traceback
try:
list_of_numbers = [1, 2, 3]
print(list_of_numbers[3])
except Exception:
print(traceback.print_stack())
In this example, we attempt to access an index of a list that does not exist, which will raise an
IndexError
. The stack trace is printed, showing the path taken to the error.
Output
:
A stack trace leading up to the error point.
Example 7: Python Print Exception Name
Printing the exception name involves capturing the exception and using
type(e).__name__
to retrieve and display the name of the exception type. This method provides clear information about the kind of error that occurred, such as
TypeError
, and is useful for logging and debugging purposes.
try:
"string" + 1
except Exception as e:
print(type(e).__name__)
In this code, we attempt to concatenate a string and an integer, which will raise a
TypeError
. The name of the exception type is printed.
Output
:
TypeError
Example 8: Python Print Exception Type
Displaying the exception type in Python is achieved by capturing the exception and utilizing
type(e)
to retrieve and print the type of exception that occurred. This method provides a clear understanding of the error category, aiding in debugging and error logging.
try:
{}["key"]
except Exception as e:
print(type(e))
Here, we attempt to access a non-existent key in a dictionary, which will raise a
KeyError
. The type of the exception is printed.
Output
:
<class 'KeyError'>
Example 9: Python Print Exception Details
Printing detailed exception information in Python involves capturing the exception and utilizing string formatting to display both the name and the message of the exception. This approach provides a detailed error report, offering insights into the type of error and the accompanying message.
try:
[] + "string"
except Exception as e:
print(f"Error: {type(e).__name__}, Message: {str(e)}")
In this example, we attempt to add a list and a string, which will raise a
TypeError
. Both the name and the message of the exception are printed.
Output
:
Error: TypeError, Message: can only concatenate list (not "str") to list
Example 10: Python Print Exception Line Number
Revealing the line number where an exception was raised in Python can be achieved using the
sys
module. By utilizing
sys.exc_info()[-1].tb_lineno
, developers can retrieve and print the line number where the exception occurred, providing a precise location of the issue in the code.
import sys
try:
x = y
except Exception as e:
print(f"Error on line {sys.exc_info()[-1].tb_lineno}: {str(e)}")
In this code, we reference an undefined variable
y
, which will raise a
NameError
. The line number and the error message are printed.
Output
:
Error on line [line_number]: name 'y' is not defined
Example 11: Python Print Exception Message Without Traceback
Printing the error message without displaying the traceback in Python involves capturing the exception and using the
print()
function to display the error message. This method provides a clean and concise error message without additional debug information.
try:
x = {}
x.append(1)
except Exception as e:
print(e)
Here, we attempt to use the
append
method (which is not applicable for dictionaries) on a dictionary, which will raise an
AttributeError
. The error message is printed without traceback.
Output
:
'dict' object has no attribute 'append'
Example 12: Python Print Exception and Continue
Printing the exception and continuing the execution involves using a try/except block to manage errors without halting the entire program. By capturing and printing the exception, developers can inform users or log the error while allowing the program to continue running subsequent code.
try:
x = 1 / 0
except Exception as e:
print(e)
print("Program continues...")
In this example, we attempt to perform a division by zero, which will raise a
ZeroDivisionError
. The error message is printed, but the program continues to execute subsequent code.
Output
:
division by zero
Program continues...
Example 13: Python Print Exception in One Line
Printing the exception in a single line of code in Python involves utilizing string formatting within the
print()
function to display a succinct and clear error message. This method maintains a compact code structure while ensuring that errors are logged or displayed.
try:
x = [1, 2, 3]
x[5]
except Exception as e:
print(f"An error occurred: {e}")
In this code, we attempt to access an index of a list that does not exist, which will raise an
IndexError
. The error message is printed in a single line.
Output
:
An error occurred: list index out of range
These examples illustrate various methods to handle and print exception information in Python, each providing a unique approach to managing errors and debugging code. The explanations, code snippets, and outputs provide a comprehensive guide to implementing these methods in Python programming.
Summary
To catch and print an exception that occurred in a code snippet, wrap it in an indented
try
block, followed by the command
"except Exception as e"
that catches the exception and saves its error message in string variable
e
. You can now print the error message with
"print(e)"
or use it for further processing.
Programmer Humor
Q
: How do you tell an introverted computer scientist from an extroverted computer scientist?
A
: An extroverted computer scientist looks at
your
shoes when he talks to you.
🧑💻
Recommended
:
Python One Line Exception Handling |
| Markdown | [Skip to content](https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/#content "Skip to content")
[](https://blog.finxter.com/)
Menu
- [🔴 YouTube](https://www.youtube.com/@finxter)
- [👑 Membership](https://blog.finxter.com/finxter-premium-membership/)
- [👩🎓 Academy](https://academy.finxter.com/)
- [📖 Books](https://blog.finxter.com/finxter-books/)
- [🎲 Puzzles](https://app.finxter.com/learn/computer/science/)
- [🤎 User Stories](https://blog.finxter.com/what-our-users-say/)
- [What Our Users Say](https://blog.finxter.com/what-our-users-say/)
- [About Finxter](https://blog.finxter.com/about/)
- [Finxter Feedback from ~1000 Python Developers](https://blog.finxter.com/finxter-feedback-from-1000-users/)
- [Video Reviews](https://blog.finxter.com/python-freelancer-course-testimonials-from-finxters/)
- [Course Review from Cristian](https://blog.finxter.com/finxter-review-become-a-freelancer-course/?tl_inbound=1&tl_target_all=1&tl_form_type=1&tl_period_type=3)
- [Course Review from Adam](https://blog.finxter.com/how-adam-earns-5000-per-month-as-a-python-freelancer-on-upwork-month-4/)
- [Review by ChatGPT](https://blog.finxter.com/what-is-finxter-is-it-trustworthy-chatgpt-answers/)
- [About Chris](https://blog.finxter.com/about-chris/)
- [Start Here ⭐](https://blog.finxter.com/make-money-ai/)

# How to Print Exception Messages in Python (Try-Except)
October 30, 2023
October 11, 2023
by [Chris](https://blog.finxter.com/author/xcentpy_cfsh849y/ "View all posts by Chris")
Python comes with extensive support for exceptions and exception handling. An exception event interrupts and, if uncaught, immediately terminates a running program. The most popular examples are the [`IndexError`](https://blog.finxter.com/python-indexerror-list-index-out-of-range/ "Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)"), [`ValueError`](https://blog.finxter.com/how-to-fix-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-use-a-any-or-a-all/ "How to Fix “ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()”"), and `TypeError`.
An exception will immediately terminate your program. To avoid this, you can **catch the exception** with a `try/except` block around the code where you expect that a certain exception may occur. Here’s how you **catch and print a given exception:**
To catch and print an exception that occurred in a code snippet, wrap it in an indented `try` block, followed by the command `"except Exception as e"` that catches the exception and saves its error message in string variable `e`. You can now print the error message with `"print(e)"` or use it for further processing.
```
try:
# ... YOUR CODE HERE ... #
except Exception as e:
# ... PRINT THE ERROR MESSAGE ... #
print(e)
```
Next, I’ll guide you through 13 hand-picked examples for specific scenarios such as with or without traceback. Exception printing is more powerful than you’d think! Let’s get started! 👇
## Example 1: Catch and Print IndexError
If you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an `IndexError` telling you that the list [index is out of range](https://blog.finxter.com/python-indexerror-list-index-out-of-range/ "Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)").
```
try:
lst = ['Alice', 'Bob', 'Carl']
print(lst[3])
except Exception as e:
print(e)
print('Am I executed?')
```
Your genius code attempts to access the fourth element in your list with index 3—that doesn’t exist\!

Fortunately, you wrapped the code in a `try/catch` block and printed the exception. The program is not terminated. Thus, it executes the final `print()` statement after the exception has been caught and handled. This is the output of the previous code snippet.
```
list index out of range
Am I executed?
```
🌍 **Recommended Tutorial:** [How to Print an Error in Python?](https://blog.finxter.com/python-return-error-from-function/)
## Example 2: Catch and Print ValueError
The [`ValueError`](https://blog.finxter.com/how-to-fix-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-use-a-any-or-a-all/ "How to Fix “ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()”") arises if you try to use wrong values in some functions. Here’s an example where the `ValueError` is raised because you tried to calculate the square root of a negative number:
```
import math
try:
a = math.sqrt(-2)
except Exception as e:
print(e)
print('Am I executed?')
```
The output shows that not only the error message but also the string `'Am I executed?'` is printed.
```
math domain error
Am I executed?
```
## Example 3: Catch and Print TypeError
Python throws the `TypeError object is not subscriptable` if you use indexing with the square bracket notation on an object that is not indexable. This is the case if the object doesn’t define the `__getitem__()` method. Here’s how you can catch the error and print it to your shell:
```
try:
variable = None
print(variable[0])
except Exception as e:
print(e)
print('Am I executed?')
```
The output shows that not only the error message but also the string `'Am I executed?'` is printed.
```
'NoneType' object is not subscriptable
Am I executed?
```
I hope you’re now able to catch and print your error messages.
## Example 4: Python Print Exception Message with str()
Use a `try/except` block, the code attempts to execute a statement and, if an exception arises, it captures and displays the corresponding error message using Python’s built-in `str()` function, aiding in the identification and resolution of issues.
```
try:
x = undefined_variable
except Exception as e:
print(str(e))
```
In this code, we reference an undefined variable, which will raise a `NameError`. The error message is then printed. Note that this is semantically equivalent to `print(e)` which internally calls `str(e)` to find a string representation of `e`.
**Output**:
```
name 'undefined_variable' is not defined
```
## Example 5: Python Print Exception Traceback
By using the `traceback` module, you can retrieve and print the entire traceback of an exception, offering a comprehensive view of where the error occurred and the call stack that led to it.
```
import traceback
try:
open("nonexistent_file.txt")
except Exception:
print(traceback.format_exc())
```
Here, we attempt to open a non-existent file, which will raise a `FileNotFoundError`. The traceback is printed, providing detailed error information.
**Output**:

```
Traceback (most recent call last):
...
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'
```
## Example 6: Python Print Exception Stack Trace
Printing the stack trace in Python involves using the `traceback` module to display the path taken by the code up to the point where the exception was raised. This method is particularly useful for understanding the sequence of function calls that led to the error, providing a clear view of the execution flow and aiding developers in pinpointing the origin of issues.
```
import traceback
try:
list_of_numbers = [1, 2, 3]
print(list_of_numbers[3])
except Exception:
print(traceback.print_stack())
```
In this example, we attempt to access an index of a list that does not exist, which will raise an `IndexError`. The stack trace is printed, showing the path taken to the error.
**Output**:

```
A stack trace leading up to the error point.
```
## Example 7: Python Print Exception Name
Printing the exception name involves capturing the exception and using `type(e).__name__` to retrieve and display the name of the exception type. This method provides clear information about the kind of error that occurred, such as `TypeError`, and is useful for logging and debugging purposes.
```
try:
"string" + 1
except Exception as e:
print(type(e).__name__)
```
In this code, we attempt to concatenate a string and an integer, which will raise a `TypeError`. The name of the exception type is printed.
**Output**:

```
TypeError
```
## Example 8: Python Print Exception Type
Displaying the exception type in Python is achieved by capturing the exception and utilizing `type(e)` to retrieve and print the type of exception that occurred. This method provides a clear understanding of the error category, aiding in debugging and error logging.
```
try:
{}["key"]
except Exception as e:
print(type(e))
```
Here, we attempt to access a non-existent key in a dictionary, which will raise a `KeyError`. The type of the exception is printed.
**Output**:
```
<class 'KeyError'>
```
## Example 9: Python Print Exception Details
Printing detailed exception information in Python involves capturing the exception and utilizing string formatting to display both the name and the message of the exception. This approach provides a detailed error report, offering insights into the type of error and the accompanying message.
```
try:
[] + "string"
except Exception as e:
print(f"Error: {type(e).__name__}, Message: {str(e)}")
```
In this example, we attempt to add a list and a string, which will raise a `TypeError`. Both the name and the message of the exception are printed.
**Output**:

```
Error: TypeError, Message: can only concatenate list (not "str") to list
```
## Example 10: Python Print Exception Line Number
Revealing the line number where an exception was raised in Python can be achieved using the `sys` module. By utilizing `sys.exc_info()[-1].tb_lineno`, developers can retrieve and print the line number where the exception occurred, providing a precise location of the issue in the code.
```
import sys
try:
x = y
except Exception as e:
print(f"Error on line {sys.exc_info()[-1].tb_lineno}: {str(e)}")
```
In this code, we reference an undefined variable `y`, which will raise a `NameError`. The line number and the error message are printed.
**Output**:

```
Error on line [line_number]: name 'y' is not defined
```
## Example 11: Python Print Exception Message Without Traceback
Printing the error message without displaying the traceback in Python involves capturing the exception and using the `print()` function to display the error message. This method provides a clean and concise error message without additional debug information.
```
try:
x = {}
x.append(1)
except Exception as e:
print(e)
```
Here, we attempt to use the `append` method (which is not applicable for dictionaries) on a dictionary, which will raise an `AttributeError`. The error message is printed without traceback.
**Output**:

```
'dict' object has no attribute 'append'
```
## Example 12: Python Print Exception and Continue
Printing the exception and continuing the execution involves using a try/except block to manage errors without halting the entire program. By capturing and printing the exception, developers can inform users or log the error while allowing the program to continue running subsequent code.
```
try:
x = 1 / 0
except Exception as e:
print(e)
print("Program continues...")
```
In this example, we attempt to perform a division by zero, which will raise a `ZeroDivisionError`. The error message is printed, but the program continues to execute subsequent code.
**Output**:

```
division by zero
Program continues...
```
## Example 13: Python Print Exception in One Line
Printing the exception in a single line of code in Python involves utilizing string formatting within the `print()` function to display a succinct and clear error message. This method maintains a compact code structure while ensuring that errors are logged or displayed.
```
try:
x = [1, 2, 3]
x[5]
except Exception as e:
print(f"An error occurred: {e}")
```
In this code, we attempt to access an index of a list that does not exist, which will raise an `IndexError`. The error message is printed in a single line.
**Output**:
```
An error occurred: list index out of range
```
These examples illustrate various methods to handle and print exception information in Python, each providing a unique approach to managing errors and debugging code. The explanations, code snippets, and outputs provide a comprehensive guide to implementing these methods in Python programming.
## Summary
To catch and print an exception that occurred in a code snippet, wrap it in an indented `try` block, followed by the command `"except Exception as e"` that catches the exception and saves its error message in string variable `e`. You can now print the error message with `"print(e)"` or use it for further processing.
## Programmer Humor
```
Q: How do you tell an introverted computer scientist from an extroverted computer scientist?
A: An extroverted computer scientist looks at your shoes when he talks to you.
```
🧑💻 **Recommended**: [Python One Line Exception Handling](https://blog.finxter.com/python-one-line-exception-handling/)
Categories [Computer Science](https://blog.finxter.com/category/computer-science/), [Error](https://blog.finxter.com/category/error/), [Python](https://blog.finxter.com/category/python/), [Scripting](https://blog.finxter.com/category/scripting/)
[Making \$1M Every Year with 0 Employees: How an Unassuming Millionaire Coded Photopea All By Himself](https://blog.finxter.com/making-1m-every-year-with-0-employees-how-an-unassuming-millionaire-coded-photopea-all-by-himself/)
[Llama vs Llama 2 – Still No Sign of Saturation\!](https://blog.finxter.com/llama-vs-llama-2-a-quick-guide-to-catch-up/)
**Be on the Right Side of Change** 🚀
The world is changing exponentially. AI eliminates entire industries. 
 [12 Ways to Make Money with AI](https://blog.finxter.com/make-money-ai/) (Article)
** [Join our free email newsletter](https://blog.finxter.com/ai/) (130k subs).**
Be on the right side of change with AI and master the art of vibe coding! 
**New Finxter Tutorials:**
- [What to Code (Book): How Indie Hackers Find Million-Dollar Micro-SaaS Ideas in the Vibe Coding Era](https://blog.finxter.com/what-to-code-book-how-indie-hackers-find-million-dollar-micro-saas-ideas-in-the-vibe-coding-era/)
- [6 Best AI Book Writers (2026): Tools for Authors & Self-Publishers](https://blog.finxter.com/best-ai-book-writers/)
- [What Your Last 10 YouTube Videos Say About Your Future Business](https://blog.finxter.com/what-your-last-10-youtube-videos-say-about-your-future-business/)
- [\[Free eBook\] Automate the Boring Stuff and Make Money with Clawdbot](https://blog.finxter.com/free-ebook-automate-the-boring-stuff-and-make-money-with-clawdbot/)
- [The JSON Trick – How to Scrape All Answers in a Subreddit? (Example Find User Needs)](https://blog.finxter.com/the-json-trick-how-to-scrape-all-answers-in-a-subreddit-example-find-user-needs/)
- [The Ghost Founder: 10 AI Startups That Can Hit \$1B Without a Single Employee](https://blog.finxter.com/the-ghost-founder-10-ai-startups-that-can-hit-1b-without-a-single-employee/)
- [Stop Testing LLMs with Poetry: Use Blackjack Instead](https://blog.finxter.com/stop-testing-llms-with-poetry-use-blackjack-instead/)
- [The “One Niche, One Channel” rule for making your first \$1k in AI](https://blog.finxter.com/the-one-niche-one-channel-rule-for-making-your-first-1k-in-ai/)
- [Dreaming of the Mediterranean: When Will Tesla FSD Hit Europe?](https://blog.finxter.com/dreaming-of-the-mediterranean-when-will-tesla-fsd-hit-europe/)
- [DriftIDE – A Startup Idea for 1B Vibe Coders \[Pitch Deck\]](https://blog.finxter.com/driftide-a-startup-idea-for-1b-vibe-coders-pitch-deck/)
**Finxter Categories:**
Categories
- [About](https://blog.finxter.com/about/)
- [Impressum](https://app.finxter.com/impressum)
- [Privacy](https://blog.finxter.com/privacy-policy/)
- [Terms](https://blog.finxter.com/terms-and-conditions-of-use/)
- [Puzzles](https://app.finxter.com/)
- [Academy](https://academy.finxter.com/)
- [Books & Courses](https://blog.finxter.com/)
- [Earnings Disclaimer](https://blog.finxter.com/earnings-disclaimer/)
- [Finxter Instagram](https://www.instagram.com/finxterdotcom/)
- [Finxter Twitter](https://twitter.com/FinxterDotCom)
- [Finxter Facebook](https://www.facebook.com/finxter)
- [Finxter YouTube](https://www.youtube.com/@finxter)
- [🔴 YouTube](https://www.youtube.com/@finxter)
- [👑 Membership](https://blog.finxter.com/finxter-premium-membership/)
- [👩🎓 Academy](https://academy.finxter.com/)
- [📖 Books](https://blog.finxter.com/finxter-books/)
- [🎲 Puzzles](https://app.finxter.com/learn/computer/science/)
- [🤎 User Stories](https://blog.finxter.com/what-our-users-say/)
- [What Our Users Say](https://blog.finxter.com/what-our-users-say/)
- [About Finxter](https://blog.finxter.com/about/)
- [Finxter Feedback from ~1000 Python Developers](https://blog.finxter.com/finxter-feedback-from-1000-users/)
- [Video Reviews](https://blog.finxter.com/python-freelancer-course-testimonials-from-finxters/)
- [Course Review from Cristian](https://blog.finxter.com/finxter-review-become-a-freelancer-course/?tl_inbound=1&tl_target_all=1&tl_form_type=1&tl_period_type=3)
- [Course Review from Adam](https://blog.finxter.com/how-adam-earns-5000-per-month-as-a-python-freelancer-on-upwork-month-4/)
- [Review by ChatGPT](https://blog.finxter.com/what-is-finxter-is-it-trustworthy-chatgpt-answers/)
- [About Chris](https://blog.finxter.com/about-chris/)
- [Start Here ⭐](https://blog.finxter.com/make-money-ai/)
© 2026 Be on the Right Side of Change • Built with [GeneratePress](https://generatepress.com/) |
| Readable Markdown | Python comes with extensive support for exceptions and exception handling. An exception event interrupts and, if uncaught, immediately terminates a running program. The most popular examples are the [`IndexError`](https://blog.finxter.com/python-indexerror-list-index-out-of-range/ "Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)"), [`ValueError`](https://blog.finxter.com/how-to-fix-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-use-a-any-or-a-all/ "How to Fix “ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()”"), and `TypeError`.
An exception will immediately terminate your program. To avoid this, you can **catch the exception** with a `try/except` block around the code where you expect that a certain exception may occur. Here’s how you **catch and print a given exception:**
To catch and print an exception that occurred in a code snippet, wrap it in an indented `try` block, followed by the command `"except Exception as e"` that catches the exception and saves its error message in string variable `e`. You can now print the error message with `"print(e)"` or use it for further processing.
```
try:
# ... YOUR CODE HERE ... #
except Exception as e:
# ... PRINT THE ERROR MESSAGE ... #
print(e)
```
Next, I’ll guide you through 13 hand-picked examples for specific scenarios such as with or without traceback. Exception printing is more powerful than you’d think! Let’s get started! 👇
## Example 1: Catch and Print IndexError
If you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an `IndexError` telling you that the list [index is out of range](https://blog.finxter.com/python-indexerror-list-index-out-of-range/ "Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)").
```
try:
lst = ['Alice', 'Bob', 'Carl']
print(lst[3])
except Exception as e:
print(e)
print('Am I executed?')
```
Your genius code attempts to access the fourth element in your list with index 3—that doesn’t exist\!

Fortunately, you wrapped the code in a `try/catch` block and printed the exception. The program is not terminated. Thus, it executes the final `print()` statement after the exception has been caught and handled. This is the output of the previous code snippet.
```
list index out of range
Am I executed?
```
🌍 **Recommended Tutorial:** [How to Print an Error in Python?](https://blog.finxter.com/python-return-error-from-function/)
## Example 2: Catch and Print ValueError
The [`ValueError`](https://blog.finxter.com/how-to-fix-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-use-a-any-or-a-all/ "How to Fix “ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()”") arises if you try to use wrong values in some functions. Here’s an example where the `ValueError` is raised because you tried to calculate the square root of a negative number:
```
import math
try:
a = math.sqrt(-2)
except Exception as e:
print(e)
print('Am I executed?')
```
The output shows that not only the error message but also the string `'Am I executed?'` is printed.
```
math domain error
Am I executed?
```
## Example 3: Catch and Print TypeError
Python throws the `TypeError object is not subscriptable` if you use indexing with the square bracket notation on an object that is not indexable. This is the case if the object doesn’t define the `__getitem__()` method. Here’s how you can catch the error and print it to your shell:
```
try:
variable = None
print(variable[0])
except Exception as e:
print(e)
print('Am I executed?')
```
The output shows that not only the error message but also the string `'Am I executed?'` is printed.
```
'NoneType' object is not subscriptable
Am I executed?
```
I hope you’re now able to catch and print your error messages.
## Example 4: Python Print Exception Message with str()
Use a `try/except` block, the code attempts to execute a statement and, if an exception arises, it captures and displays the corresponding error message using Python’s built-in `str()` function, aiding in the identification and resolution of issues.
```
try:
x = undefined_variable
except Exception as e:
print(str(e))
```
In this code, we reference an undefined variable, which will raise a `NameError`. The error message is then printed. Note that this is semantically equivalent to `print(e)` which internally calls `str(e)` to find a string representation of `e`.
**Output**:
```
name 'undefined_variable' is not defined
```
## Example 5: Python Print Exception Traceback
By using the `traceback` module, you can retrieve and print the entire traceback of an exception, offering a comprehensive view of where the error occurred and the call stack that led to it.
```
import traceback
try:
open("nonexistent_file.txt")
except Exception:
print(traceback.format_exc())
```
Here, we attempt to open a non-existent file, which will raise a `FileNotFoundError`. The traceback is printed, providing detailed error information.
**Output**:

```
Traceback (most recent call last):
...
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'
```
## Example 6: Python Print Exception Stack Trace
Printing the stack trace in Python involves using the `traceback` module to display the path taken by the code up to the point where the exception was raised. This method is particularly useful for understanding the sequence of function calls that led to the error, providing a clear view of the execution flow and aiding developers in pinpointing the origin of issues.
```
import traceback
try:
list_of_numbers = [1, 2, 3]
print(list_of_numbers[3])
except Exception:
print(traceback.print_stack())
```
In this example, we attempt to access an index of a list that does not exist, which will raise an `IndexError`. The stack trace is printed, showing the path taken to the error.
**Output**:

```
A stack trace leading up to the error point.
```
## Example 7: Python Print Exception Name
Printing the exception name involves capturing the exception and using `type(e).__name__` to retrieve and display the name of the exception type. This method provides clear information about the kind of error that occurred, such as `TypeError`, and is useful for logging and debugging purposes.
```
try:
"string" + 1
except Exception as e:
print(type(e).__name__)
```
In this code, we attempt to concatenate a string and an integer, which will raise a `TypeError`. The name of the exception type is printed.
**Output**:

```
TypeError
```
## Example 8: Python Print Exception Type
Displaying the exception type in Python is achieved by capturing the exception and utilizing `type(e)` to retrieve and print the type of exception that occurred. This method provides a clear understanding of the error category, aiding in debugging and error logging.
```
try:
{}["key"]
except Exception as e:
print(type(e))
```
Here, we attempt to access a non-existent key in a dictionary, which will raise a `KeyError`. The type of the exception is printed.
**Output**:
```
<class 'KeyError'>
```
## Example 9: Python Print Exception Details
Printing detailed exception information in Python involves capturing the exception and utilizing string formatting to display both the name and the message of the exception. This approach provides a detailed error report, offering insights into the type of error and the accompanying message.
```
try:
[] + "string"
except Exception as e:
print(f"Error: {type(e).__name__}, Message: {str(e)}")
```
In this example, we attempt to add a list and a string, which will raise a `TypeError`. Both the name and the message of the exception are printed.
**Output**:

```
Error: TypeError, Message: can only concatenate list (not "str") to list
```
## Example 10: Python Print Exception Line Number
Revealing the line number where an exception was raised in Python can be achieved using the `sys` module. By utilizing `sys.exc_info()[-1].tb_lineno`, developers can retrieve and print the line number where the exception occurred, providing a precise location of the issue in the code.
```
import sys
try:
x = y
except Exception as e:
print(f"Error on line {sys.exc_info()[-1].tb_lineno}: {str(e)}")
```
In this code, we reference an undefined variable `y`, which will raise a `NameError`. The line number and the error message are printed.
**Output**:

```
Error on line [line_number]: name 'y' is not defined
```
## Example 11: Python Print Exception Message Without Traceback
Printing the error message without displaying the traceback in Python involves capturing the exception and using the `print()` function to display the error message. This method provides a clean and concise error message without additional debug information.
```
try:
x = {}
x.append(1)
except Exception as e:
print(e)
```
Here, we attempt to use the `append` method (which is not applicable for dictionaries) on a dictionary, which will raise an `AttributeError`. The error message is printed without traceback.
**Output**:

```
'dict' object has no attribute 'append'
```
## Example 12: Python Print Exception and Continue
Printing the exception and continuing the execution involves using a try/except block to manage errors without halting the entire program. By capturing and printing the exception, developers can inform users or log the error while allowing the program to continue running subsequent code.
```
try:
x = 1 / 0
except Exception as e:
print(e)
print("Program continues...")
```
In this example, we attempt to perform a division by zero, which will raise a `ZeroDivisionError`. The error message is printed, but the program continues to execute subsequent code.
**Output**:

```
division by zero
Program continues...
```
## Example 13: Python Print Exception in One Line
Printing the exception in a single line of code in Python involves utilizing string formatting within the `print()` function to display a succinct and clear error message. This method maintains a compact code structure while ensuring that errors are logged or displayed.
```
try:
x = [1, 2, 3]
x[5]
except Exception as e:
print(f"An error occurred: {e}")
```
In this code, we attempt to access an index of a list that does not exist, which will raise an `IndexError`. The error message is printed in a single line.
**Output**:
```
An error occurred: list index out of range
```
These examples illustrate various methods to handle and print exception information in Python, each providing a unique approach to managing errors and debugging code. The explanations, code snippets, and outputs provide a comprehensive guide to implementing these methods in Python programming.
## Summary
To catch and print an exception that occurred in a code snippet, wrap it in an indented `try` block, followed by the command `"except Exception as e"` that catches the exception and saves its error message in string variable `e`. You can now print the error message with `"print(e)"` or use it for further processing.
## Programmer Humor
```
Q: How do you tell an introverted computer scientist from an extroverted computer scientist?
A: An extroverted computer scientist looks at your shoes when he talks to you.
```
🧑💻 **Recommended**: [Python One Line Exception Handling](https://blog.finxter.com/python-one-line-exception-handling/) |
| Shard | 121 (laksa) |
| Root Hash | 6977083233833885521 |
| Unparsed URL | com,finxter!blog,/how-to-catch-and-print-exception-messages-in-python/ s443 |