Properly handling exceptions in context manager