ℹ️ 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.1 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://rollbar.com/blog/what-is-except-exception-as-e-in-python/ |
| Last Crawled | 2026-04-11 06:48:06 (3 days ago) |
| First Indexed | 2024-07-17 11:11:20 (1 year ago) |
| HTTP Status Code | 200 |
| Meta Title | What is “except Exception as e” in Python? | Rollbar |
| Meta Description | Wrap risky code in a try block and catch exceptions in an except block. The exception is assigned to the variable e for further use. |
| Meta Canonical | null |
| Boilerpipe Text | except Exception as e
is a construct in Python used for exception handling. It allows you to catch exceptions that occur during the execution of a block of code by using a
try
block to wrap the code that might raise an exception, and an
except
block to catch and handle the exception.
The
Exception
part specifies that any exception of this type or its subclasses should be caught, and the
as e
part assigns the caught exception to a variable
e
, which you can then use to access details about the exception.
Take a look at this example:
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}")
Running that will print:
An error occurred: division by zero
This is what happens step-by-step:
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".
The
print(f"An error occurred: {e}")
statement prints the error message to the console.
When using
except Exception as e
, here are a few things to keep in mind for handling exceptions effectively:
Catch specific exceptions rather than all exceptions
Catching all exceptions with
except Exception as e
can mask unexpected errors and make debugging more difficult.
đź’ˇBest Practice:
Whenever possible, catch specific exceptions (e.g.,
except ZeroDivisionError as e
) to handle different error conditions appropriately.
Clean up resources
Ensure that resources (e.g., files or network connections) are properly released even if an exception occurs.
đź’ˇBest Practice:
Use a
finally
block to clean up resources. Like this:
try:
file = open("data.txt")
result = 10 / 0
except Exception as e:
print(f"An error occurred: {e}")
finally:
file.close()
Use chained exceptions to catch one exception and raise another
Chained exceptions allow you to catch one exception and raise another while preserving the original exception's context. This is helpful for debugging because it provides a clear trail of what went wrong.
đź’ˇBest Practice:
Each function should handle its own specific concerns but communicate issues up the call stack with chained exceptions.
Imagine a scenario where you have a function that validates user input and another function that processes that input. If the input is invalid, the validation function raises a specific error, and the processing function raises a more general error to be handled higher up in the call stack.
class InvalidInputError(Exception):
"""Custom exception for invalid user input."""
pass
def validate_input(user_input):
if not user_input.isdigit():
raise InvalidInputError("Input must be a number")
def process_input(user_input):
try:
validate_input(user_input)
# Process the input assuming it's valid (e.g., convert to int)
number = int(user_input)
return number * 2
except InvalidInputError as e:
raise ValueError("Failed to process input due to invalid data") from e
def main():
user_input = "abc" # Simulate invalid user input
try:
result = process_input(user_input)
print(f"Processing result: {result}")
except ValueError as e:
print(f"An error occurred: {e}")
print(f"Original exception: {e.__cause__}")
if __name__ == "__main__":
main()
When you run that code, the output will be:
An error occurred: Failed to process input due to invalid data
Original exception: Input must be a number
The
main
function catches the
ValueError
raised by
process_input
and prints both the general error message and the original exception.
Log exceptions
Logging exceptions helps with debugging and maintaining a record of errors.
đź’ˇBest Practice:
Use the exception monitoring SDK
Rollbar
which gives you a real-time feed of all errors, including unhandled exceptions. Rollbar's revolutionary grouping engine uses machine learning to determine patterns on an ongoing basis and identify unique errors.
import rollbar
# Initialize Rollbar with your access token
rollbar.init('YOUR_ACCESS_TOKEN')
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}")
# Log the exception to Rollbar
rollbar.report_exc_info()
When you run this code, any exceptions caught in the
except
block will be logged to Rollbar, allowing you to find and fix errors in your code faster.
Try Rollbar today
! |
| Markdown | [](https://rollbar.com/) [](https://rollbar.com/)
- [Platform]()
- - [Error monitoring](https://rollbar.com/error-monitoring)
- [Session Replay](https://rollbar.com/session-replay)
- [...and more](https://rollbar.com/platform)
- [Languages](https://rollbar.com/languages)
- [Integrations](https://rollbar.com/integrations)
- [Company](https://rollbar.com/company)
- [Pricing](https://rollbar.com/pricing/)
- [Docs](https://rollbar.com/developer/)
- - [Documentation](https://docs.rollbar.com/docs)
- [Roadmap](https://rollbar.notion.site/17484017245c4d49bba56207b735c8e4?v=126edaeb35904dbb82ffc3d0971e0b2d)
- [System Status](https://status.rollbar.com/)
- [Blog](https://rollbar.com/blog)
- [Videos](https://www.youtube.com/RollbarApp)
- [Log in](https://rollbar.com/login/)
- [Try free](https://rollbar.com/signup/)
- [Log in](https://rollbar.com/login/)
- [Try free](https://rollbar.com/signup/)
[Blog](https://rollbar.com/blog/) \|
- [Code Tutorials](https://rollbar.com/blog/category/tutorials/)
- [Python](https://rollbar.com/blog/category/tutorials/python/)
# What is “except Exception as e” in Python?
Jun 24, 2024

##### Table of Contents
`except Exception as e` is a construct in Python used for exception handling. It allows you to catch exceptions that occur during the execution of a block of code by using a `try` block to wrap the code that might raise an exception, and an `except` block to catch and handle the exception.
The `Exception` part specifies that any exception of this type or its subclasses should be caught, and the `as e` part assigns the caught exception to a variable `e`, which you can then use to access details about the exception.
Take a look at this example:
```
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}")
```
Running that will print:
```
An error occurred: division by zero
```
This is what happens step-by-step:
1. The try block attempts to execute `result = 10 / 0`.
2. Division by zero is not allowed so a `ZeroDivisionError` is raised.
3. The `except Exception as e` block catches the `ZeroDivisionError`.
4. The exception is assigned to the variable `e`, which contains the error message "division by zero".
5. The `print(f"An error occurred: {e}")` statement prints the error message to the console.
When using `except Exception as e`, here are a few things to keep in mind for handling exceptions effectively:
## Catch specific exceptions rather than all exceptions
Catching all exceptions with `except Exception as e` can mask unexpected errors and make debugging more difficult.
**đź’ˇBest Practice:** Whenever possible, catch specific exceptions (e.g., `except ZeroDivisionError as e`) to handle different error conditions appropriately.
## Clean up resources
Ensure that resources (e.g., files or network connections) are properly released even if an exception occurs.
**đź’ˇBest Practice:** Use a `finally` block to clean up resources. Like this:
```
try:
file = open("data.txt")
result = 10 / 0
except Exception as e:
print(f"An error occurred: {e}")
finally:
file.close()
```
## Use chained exceptions to catch one exception and raise another
Chained exceptions allow you to catch one exception and raise another while preserving the original exception's context. This is helpful for debugging because it provides a clear trail of what went wrong.
**đź’ˇBest Practice:** Each function should handle its own specific concerns but communicate issues up the call stack with chained exceptions.
Imagine a scenario where you have a function that validates user input and another function that processes that input. If the input is invalid, the validation function raises a specific error, and the processing function raises a more general error to be handled higher up in the call stack.
```
class InvalidInputError(Exception):
"""Custom exception for invalid user input."""
pass
def validate_input(user_input):
if not user_input.isdigit():
raise InvalidInputError("Input must be a number")
def process_input(user_input):
try:
validate_input(user_input)
# Process the input assuming it's valid (e.g., convert to int)
number = int(user_input)
return number * 2
except InvalidInputError as e:
raise ValueError("Failed to process input due to invalid data") from e
def main():
user_input = "abc" # Simulate invalid user input
try:
result = process_input(user_input)
print(f"Processing result: {result}")
except ValueError as e:
print(f"An error occurred: {e}")
print(f"Original exception: {e.__cause__}")
if __name__ == "__main__":
main()
```
When you run that code, the output will be:
```
An error occurred: Failed to process input due to invalid data
Original exception: Input must be a number
```
The `main` function catches the `ValueError` raised by `process_input` and prints both the general error message and the original exception.
## Log exceptions
Logging exceptions helps with debugging and maintaining a record of errors.
**đź’ˇBest Practice:** Use the exception monitoring SDK [Rollbar](https://rollbar.com/platforms/python-error-tracking/) which gives you a real-time feed of all errors, including unhandled exceptions. Rollbar's revolutionary grouping engine uses machine learning to determine patterns on an ongoing basis and identify unique errors.
```
import rollbar
# Initialize Rollbar with your access token
rollbar.init('YOUR_ACCESS_TOKEN')
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}")
# Log the exception to Rollbar
rollbar.report_exc_info()
```
When you run this code, any exceptions caught in the `except` block will be logged to Rollbar, allowing you to find and fix errors in your code faster. [Try Rollbar today](https://rollbar.com/signup/)\!
- [Python](https://rollbar.com/blog/tag/python/ "Python")
## Related Resources
- [](https://rollbar.com/blog/python-catching-multiple-exceptions/)
[How to Catch Multiple Exceptions in Python](https://rollbar.com/blog/python-catching-multiple-exceptions/)
- [](https://rollbar.com/blog/how-to-fix-indexerror-list-assignment-index-out-of-range-python/)
[How to Fix “IndexError: List Assignment Index Out of Range” in Python](https://rollbar.com/blog/how-to-fix-indexerror-list-assignment-index-out-of-range-python/)
- [](https://rollbar.com/blog/python-syntaxerror/)
[How to Fix Invalid SyntaxError in Python](https://rollbar.com/blog/python-syntaxerror/)

## Build with confidence. Release with clarity.
Rollbar helps you track what breaks, understand why, and improve what comes next.
âś“ 5K free events per month, forever
âś“ 14-day full feature trial
âś“ Easy and quick installation
[Get started in minutes](https://rollbar.com/signup/)
Plans starting at \$0. Take off with our 14-day full feature Free Trial.
[![Rollbar]()](https://rollbar.com/)
Product
- [Product](https://rollbar.com/discover/)
- [Pricing](https://rollbar.com/pricing/)
- [Customers](https://rollbar.com/customers/)
- [Platforms](https://rollbar.com/platforms/)
- [Integrations](https://rollbar.com/integrations/)
- [Changelog](https://changelog.rollbar.com/)
- [Roadmap](https://rollbar.notion.site/17484017245c4d49bba56207b735c8e4?v=126edaeb35904dbb82ffc3d0971e0b2d)
Languages/Frameworks
- [JavaScript](https://rollbar.com/platforms/javascript-error-tracking/)
- [Go](https://rollbar.com/platforms/go-error-tracking/)
- [iOS](https://rollbar.com/platforms/ios-error-tracking/)
- [Java](https://rollbar.com/platforms/java-error-tracking/)
- [Next.js](https://rollbar.com/platforms/javascript-error-tracking/)
- [.NET](https://rollbar.com/platforms/dotnet-error-tracking/)
- [React](https://rollbar.com/platforms/react-error-tracking/)
- [Node.js](https://rollbar.com/platforms/node-error-tracking/)
- [React Native](https://rollbar.com/platforms/react-native-error-tracking/)
- [PHP](https://rollbar.com/platforms/php-error-tracking/)
- [Rails](https://rollbar.com/platforms/rails-error-tracking/)
- [Python](https://rollbar.com/platforms/python-error-tracking/)
- [Ruby](https://rollbar.com/platforms/ruby-error-tracking/)
- [Django](https://rollbar.com/platforms/django-error-tracking/)
- [More…](https://rollbar.com/platforms/)
Documentation
- [Docs Overview](https://docs.rollbar.com/docs)
- [Setting up Rollbar](https://docs.rollbar.com/docs/setup)
- [Notifications](https://docs.rollbar.com/docs/notifications)
- [Deploy Tracking](https://docs.rollbar.com/docs/deploy-tracking)
- [Telemetry](https://docs.rollbar.com/docs/telemetry)
- [Security & Compliance](https://docs.rollbar.com/docs/security)
- [API](https://docs.rollbar.com/reference/getting-started-1)
Company
- [About Us](https://rollbar.com/about/)
- [Careers](https://rollbar.com/careers/)
- [Contact Us](https://rollbar.com/contact/)
[![Github]()](https://github.com/rollbar) [![Twitter]()](https://twitter.com/rollbar) [![LinkedIn]()](https://www.linkedin.com/company/rollbar/)
© 2012-25 Rollbar Inc.
- [Privacy Policy](https://docs.rollbar.com/docs/privacy-policy)
- [Terms of Service](https://docs.rollbar.com/docs/terms-of-service) |
| Readable Markdown | `except Exception as e` is a construct in Python used for exception handling. It allows you to catch exceptions that occur during the execution of a block of code by using a `try` block to wrap the code that might raise an exception, and an `except` block to catch and handle the exception.
The `Exception` part specifies that any exception of this type or its subclasses should be caught, and the `as e` part assigns the caught exception to a variable `e`, which you can then use to access details about the exception.
Take a look at this example:
```
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}")
```
Running that will print:
```
An error occurred: division by zero
```
This is what happens step-by-step:
1. The try block attempts to execute `result = 10 / 0`.
2. Division by zero is not allowed so a `ZeroDivisionError` is raised.
3. The `except Exception as e` block catches the `ZeroDivisionError`.
4. The exception is assigned to the variable `e`, which contains the error message "division by zero".
5. The `print(f"An error occurred: {e}")` statement prints the error message to the console.
When using `except Exception as e`, here are a few things to keep in mind for handling exceptions effectively:
## Catch specific exceptions rather than all exceptions
Catching all exceptions with `except Exception as e` can mask unexpected errors and make debugging more difficult.
**đź’ˇBest Practice:** Whenever possible, catch specific exceptions (e.g., `except ZeroDivisionError as e`) to handle different error conditions appropriately.
## Clean up resources
Ensure that resources (e.g., files or network connections) are properly released even if an exception occurs.
**đź’ˇBest Practice:** Use a `finally` block to clean up resources. Like this:
```
try:
file = open("data.txt")
result = 10 / 0
except Exception as e:
print(f"An error occurred: {e}")
finally:
file.close()
```
## Use chained exceptions to catch one exception and raise another
Chained exceptions allow you to catch one exception and raise another while preserving the original exception's context. This is helpful for debugging because it provides a clear trail of what went wrong.
**đź’ˇBest Practice:** Each function should handle its own specific concerns but communicate issues up the call stack with chained exceptions.
Imagine a scenario where you have a function that validates user input and another function that processes that input. If the input is invalid, the validation function raises a specific error, and the processing function raises a more general error to be handled higher up in the call stack.
```
class InvalidInputError(Exception):
"""Custom exception for invalid user input."""
pass
def validate_input(user_input):
if not user_input.isdigit():
raise InvalidInputError("Input must be a number")
def process_input(user_input):
try:
validate_input(user_input)
# Process the input assuming it's valid (e.g., convert to int)
number = int(user_input)
return number * 2
except InvalidInputError as e:
raise ValueError("Failed to process input due to invalid data") from e
def main():
user_input = "abc" # Simulate invalid user input
try:
result = process_input(user_input)
print(f"Processing result: {result}")
except ValueError as e:
print(f"An error occurred: {e}")
print(f"Original exception: {e.__cause__}")
if __name__ == "__main__":
main()
```
When you run that code, the output will be:
```
An error occurred: Failed to process input due to invalid data
Original exception: Input must be a number
```
The `main` function catches the `ValueError` raised by `process_input` and prints both the general error message and the original exception.
## Log exceptions
Logging exceptions helps with debugging and maintaining a record of errors.
**đź’ˇBest Practice:** Use the exception monitoring SDK [Rollbar](https://rollbar.com/platforms/python-error-tracking/) which gives you a real-time feed of all errors, including unhandled exceptions. Rollbar's revolutionary grouping engine uses machine learning to determine patterns on an ongoing basis and identify unique errors.
```
import rollbar
# Initialize Rollbar with your access token
rollbar.init('YOUR_ACCESS_TOKEN')
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}")
# Log the exception to Rollbar
rollbar.report_exc_info()
```
When you run this code, any exceptions caught in the `except` block will be logged to Rollbar, allowing you to find and fix errors in your code faster. [Try Rollbar today](https://rollbar.com/signup/)\! |
| Shard | 159 (laksa) |
| Root Hash | 12444683554500093559 |
| Unparsed URL | com,rollbar!/blog/what-is-except-exception-as-e-in-python/ s443 |