0

I am trying to understand the with statement in python but I don't get how it does exception handling.

For example, we have this code

file = open('file-path', 'w') 
try: 
    file.write('Lorem ipsum') 
finally: 
    file.close() 

and then this code

with open('file_path', 'w') as file:
    file.write('hello world !')

Here when is file.close() is called? From this question I think because python have entry and exit function (and exit function is called by itself when file.write(); is over?) but then how are we going to do exception handling (catch) statement in particular?

Also, what if we don't write finally in first snippet, it won't close connection by itself?

file = open('file-path', 'w') 
try: 
    file.write('Lorem ipsum') 
2
  • Not sure what exception handling has to do with this. The with block executes an exit function at the end of the block. In the case of a file handler, the exit function closes the file. No exception happening here. What you do with try..finally is simply ensure that file.close will always be called, even if an exception should happen in file.write. A with block as the same effect. Commented Nov 16, 2022 at 12:32
  • A try without an except or finally block is a syntax error BTW… Commented Nov 16, 2022 at 12:33

1 Answer 1

3

When using with statements, __exit__ will be called whenever we leave the with block, regardless of if we leave it due to exception or if we just finished executing contained code normally.

If any code contained in the with block causes an exception, it will cause the __exit__ to run and then propagate the exception to the surrounding try/except block.

This snippet (added finally: pass for the sake of syntax correctness):

file = open('file-path', 'w') 
try: 
    file.write('Lorem ipsum')
finally:
    pass

will never cause the file to be closed, so it will remain open for the whole run of the program (assuming close is not called anywhere else).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.