Alwaysblue
Alwaysblue

Reputation: 11830

Understanding exception handling in with statement in python

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') 

Upvotes: 0

Views: 115

Answers (1)

matszwecja
matszwecja

Reputation: 7970

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).

Upvotes: 2

Related Questions