python
with open('file.txt', 'w') as file:
file.write('Hello, world!')
python
class MyContext:
def __enter__(self):
print('Entering context')
def __exit__(self, exc_type, exc_val, exc_tb):
print('Exiting context')
if exc_type is not None:
print('An exception occurred:', exc_val)
with MyContext() as context:
print('Inside context')
raise ValueError('Oops!')
Entering context
Inside context
Exiting context
An exception occurred: Oops!
Traceback (most recent call last):
File "main.py", line 12, in <module>
raise ValueError('Oops!')
ValueError: Oops!