Peter Hansen wrote: > 3c273 wrote: >> "Robert Kern" <[EMAIL PROTECTED]> wrote in message >> news:[EMAIL PROTECTED] >> >>> Paul Rubin wrote: >>> >>>> Say that the open is inside the try block. If the file can't be >>>> opened, then 'open' raises an exception, 'f' doesn't get set, and then >>>> the 'finally' clause tries to close f. f might have been previously >>>> bound to some other file (which still has other handles alive) and so >>>> the wrong file gets closed. >>> And even if 'f' wasn't bound to anything, you will get a NameError instead >> of >> >>> the exception that you're really interested in seeing. >> >> Thanks to both of you. So in order to be thorough, should I be doing: >> try: >> f=open('file') >> except: IOError: >> print 'doesn't exist' >> so_something_else_instead() >> >> try: >> contents = f.read() >> finally: >> f.close() > > Unfortunately, that would still have trouble if the first exception > handler was executed, since then you'd try read from f, which would fail > with another exception, and then you'd try to close f, and that would > probably fail and raise an exception that isn't caught anywhere. > > So this is better, though probably excessive in small scripts: > > try: > f = open('file') > except IOError: > # do something else > else: > try: > content = f.read() > finally: > f.close() > > This takes advantage of "else" on try statements, which executes only if > the except statement is not executed. > > -Peter >
this is what i always do for files and other types of resources: if it's a low-level routine, i usually let any exceptions bubble up to a higher level routine that cares or knows what to do. f = open('file') try: # do something finally: f.close() if i really want to handle the exception, then i handle it at a conceptually "higher" level by wrapping it in an exception which is basically what some higher-level routine would do anyways. try: f = open('file) try: # do something finally: f.close() except IOError: # handle exceptions bryan -- http://mail.python.org/mailman/listinfo/python-list