exception handling in complex Python programs

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Aug 21 09:34:47 CEST 2008

dbpokorny at gmail.com a écrit :
> On Aug 19, 4:12 pm, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> wrote:
>> On Tue, 19 Aug 2008 11:07:39 -0700, dbpoko... at gmail.com wrote:
>>>   def do_something(filename):
>>>     if not os.access(filename,os.R_OK):
>>>       return err(...)
>>>     f = open(filename)
>>>     ...
>> You're running on a multitasking modern machine, right? What happens when
>> some other process deletes filename, or changes its permissions, in the
>> time after you check for access but before you actually open it?
> This is a good point - if you want to use the correct way of opening
> files, and
> you don't want to worry about tracking down exception types, then we
> can probably
> agree that the following is the simplest, easiest-to-remember way:
>   def do_something(filename):
>     try:
>       f = open(filename)
>     except:
>       <handle exception>
>     ...

Still not correct IMHO - bare except clauses are BAD. You want:

        f = open(filename)
      except IOError, e:
        <handle exception>

> Opening files is a special case where EAFP is the only correct
> solution (AFAIK). I still liberally sprinkle LBYL-style "assert
> isinstance(...)" 

Which defeats the whole point of dynamic typing...

> and other similar assertions in routines.

> The point
> is that EAFP conflicts with the interest of reporting errors as soon
> as possible (on which much has been written see, for instance Ch. 8 -
> Defensive Programming in Code Complete),

Defensive programming makes sense in the context of a low-level language 
   like C where errors can lead to dramatic results. In high-level 
languages like Python, the worse thing that an unhandled exception can 
cause is an abrupt termination of the process and a nice traceback on 
screen. In this context, defensive programming is mostly a waste of time 
- if you can't *correctly* handle the exception where it happens, then 
doing nothing is the better solution.

My 2 cents...

More information about the Python-list mailing list