Scanning a file

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Oct 30 23:20:02 CET 2005


On Sun, 30 Oct 2005 08:35:12 -0700, Alex Martelli wrote:

> Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
>    ...
>> > 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?
> 
> That depends on your application, and what you're trying to accomplish
> at this point.
> 
> 
>> Is there a canonical list somewhere that states every possible exception
>> from a file open or close?
> 
> No.  But if you get a totally unexpected exception, 

I'm more concerned about getting an expected exception -- or more
accurately, *missing* an expected exception. Matching on Exception is too
high. EOFError will probably need to be handled separately, since it often
isn't an error at all, just a change of state. IOError is the bad one.
What else can go wrong?


> something that shows
> the world has gone crazy and most likely any further action you perform
> would run the risk of damaging the user's persistent data since the
> macchine appears to be careening wildly out of control... WHY would you
> want to perform any further action?

In circumstances where, as you put it, the hard disk has crashed, the CPU
is on strike, or the memory has melted down, not only can you not recover
gracefully, but you probably can't even fail gracefully -- at least not
without a special purpose fail-safe operating system.

I'm not concerned with mylist.append(None) unexpectedly -- and
impossibly? -- raising an ImportError. I can't predict every way things
can explode, and even if they do, I can't safely recover from them. But I
can fail gracefully from *expected* errors: rather than the application
just crashing, I can at least try to put up a somewhat informative dialog
box, or at least print something to the console. If opening a preferences
file fails, I can fall back on default settings. If writing the
preferences file fails, I can tell the user that their settings won't be
saved, and continue. Just because the disk is full or their disk quota is
exceeded, doesn't necessarily mean the app can't continue with the job on
hand.


-- 
Steven.




More information about the Python-list mailing list