advanced patterns with Python's `with` Statement in Custom Context Managers
I just started working with I'm sure I'm missing something obvious here, but I've been banging my head against this for hours. I'm working with an unexpected behavior while using Python's `with` statement with a custom context manager. I've implemented a simple context manager that is supposed to manage a database connection. However, when I try to use it, it appears that the connection is not being properly closed after the block is executed, leading to a resource leak. Here's a minimal version of my context manager: ```python class DatabaseConnection: def __enter__(self): self.conn = self.connect_to_database() return self.conn def __exit__(self, exc_type, exc_val, exc_tb): self.close_connection(self.conn) def connect_to_database(self): print('Connecting to database...') # Simulate a database connection return 'db_connection' def close_connection(self, conn): print('Closing the database connection...') # Simulate closing the connection # Usage of the context manager with DatabaseConnection() as db: print('Using the database:', db) # Simulate an behavior raise ValueError('An behavior occurred!') ``` When I run this code, I expect to see 'Closing the database connection...' printed after the `ValueError` is raised. However, I'm not seeing that output, and it appears that the `__exit__` method is not being called. I've tried adding print statements in the `__exit__` method, but there is nothing appearing in the console. I've confirmed that my Python version is 3.8.5. Can anyone guide to understand why the `__exit__` method isn't being executed in this case? Am I missing something in my context manager implementation or how I'm raising the exception? Any feedback is welcome! I'm developing on Windows 10 with Python. Is there a simpler solution I'm overlooking?