[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

FDs will be closed after exception automatically in python2.7?

On 06/10/2019 04:18 AM, lampahome wrote:
> as title,
> I confused will fd will be close after exception automatically?
> Like:
> try:
>     fd=open("file","w+")
>     fd.get() //any useless function of fd
> except Exception:
>     print 'hi'

No.  What if you want to work with the fd object after dealing with the

Probably you should be using Python 3, which uses a print() function.
But even in Python 2.7, the recommended way to do this is like this:

fd = open("file","w+")
with fd:

After the "with" block exits, the fd object is automatically closed.
This happens regardless of whether an exception occurred within the with
block or not.  You may use try and except within the with block.
Normally I wouldn't bother, though.

Be careful about catching exceptions.  In most cases, it is not
appropriate in my opinion to "except Exception" which will catch *all*
exceptions including syntax errors in your code.

Only catch exceptions that your code is specifically equipped to deal
with (expecting).  For example, if a user provides a file name, and you
open it, you may want to catch the FileNotFound exception, in order to
inform the user and prompt for a new file name.

Exceptions that your code is not expecting and cannot handle should be
left alone to bubble up and be caught somewhere else, or crash the
program with a traceback, which will aid in debugging.