Manejo de excepciones en un administrador de contexto
En este paso, mejorará el administrador de contexto para manejar las excepciones que pueden ocurrir dentro del contexto. Echa un vistazo al administrador de contexto InterstellarPortal modificado.
En /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
Ejecuta el script:
python context_manager.py
La información siguiente debe aparecer en tu 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