On Sat, 29 Oct 2005 16:41:42 -0700, Alex Martelli wrote: > 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.
Of course. That's why I said "something like this" and not "do this" :-) I don't expect people to "handle" exceptions with a print statement in anything more serious than a throw-away script. For serious, production-level code, more often than not you will end up spending more time and effort handling errors than you spend on handling the task your application is actually meant to do. But I suspect I'm not telling Alex anything he doesn't already know. > 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. What would you -- or anyone else -- recommend as a better approach? Is there a canonical list somewhere that states every possible exception from a file open or close? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list