Handling Exceptions in a Context Manager
In this step, you will enhance the context manager to handle exceptions that may occur within the context. Take a look at the modified InterstellarPortal context manager.
In /home/labex/project/context_manager.py
:
class InterstellarPortal:
def __enter__(self):
print("Opening the portal to another dimension")
def __exit__(self, exc_type, exc_val, exc_tb):
print("Closing the portal")
if exc_type is not None:
print(f"An error occurred: {exc_type}, {exc_val}")
## Example usage
with InterstellarPortal():
print("Stepping into the interstellar portal")
1 / 0 ## Simulate an error
Run the script:
python context_manager.py
The information below should be displayed on your terminal:
Opening the portal to another dimension
Stepping into the interstellar portal
Closing the portal
An error occurred: <class 'ZeroDivisionError'>, division by zero
Traceback (most recent call last):
File "/home/labex/project/context_manager.py", line 13, in <module>
1 / 0 ## Simulate an error
ZeroDivisionError: division by zero