
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Rethrow Python Exception with New Type
In Python, you can catch an exception and raise a new one, while keeping the original exception for more details. This helps when you want to change a low-level error into a clearer, higher-level error that fits your application better.
Sometimes, catching a specific exception and raising a new one helps you to handle problems or give a clearer message. Python lets you do this using the raise NewException from OriginalException syntax.
Rethrowing with a New Exception Type
You can rethrow an exception using the from keyword to keep the original error details and traceback. This helps you provide a new error while still showing where the original problem happened.
Example: Converting ZeroDivisionError to ValueError
In this example, we catch a ZeroDivisionError and raise a ValueError instead, keeping the original exception context -
def divide(a, b): try: return a / b except ZeroDivisionError as e: raise ValueError("Division failed due to zero denominator") from e try: result = divide(10, 0) except ValueError as e: print("Caught ValueError:", e) print("Original cause:", e.__cause__)
Here, the new exception provides a clearer message, but the original cause is still accessible using e.__cause__ attribute -
Caught ValueError: Division failed due to zero denominator Original cause: division by zero
Rethrowing Without Preserving Original Exception
You can raise a new exception without linking it to the original error by omitting the from keyword. This means the new error will appear on its own, without showing the original traceback.
Example
In this example, we replace the original exception but don't keep a reference to it -
def parse_number(s): try: return int(s) except ValueError: raise TypeError("Expected a numeric string") try: result = parse_number("abc") except TypeError as e: print("Caught TypeError:", e)
In this case, only the new exception is shown. The original ValueError is not accessible -
Caught TypeError: Expected a numeric string