Steven D'Aprano <[EMAIL PROTECTED]> wrote: ... > I should also point out that for really serious work, the idiom: > > f = file("parrot") > handle(f) > f.close() > > is insufficiently robust for production level code. That was a detail I > didn't think I needed to drop on the original newbie poster, but depending > on how paranoid you are, or how many exceptions you want to insulate the > user from, something like this might be needed: > > try: > f = file("parrot") > try: > handle(f) > finally: > try: > f.close() > except: > print "The file could not be closed; see your sys admin." > except: > print "The file could not be opened."
The inner try/finally is fine, but both the try/except are total, utter, unmitigated disasters: they will hide a lot of information about problems, let the program continue in a totally erroneous state, give mistaken messages if handle(f) causes any kind of error totally unrelated to opening the file (or if the user hits control-C during a lengthy run of handle(f)), emit messages that can erroneously end up in the redirected stdout of your program... VERY, VERY bad things. Don't ever catch and ``handle'' exceptions in such ways. In particular, each time you're thinking of writing a bare 'except:' clause, think again, and you'll most likely find a much better approach. Alex -- http://mail.python.org/mailman/listinfo/python-list