Re Interest check in some delicious syntactic sugar for "except:pass"

Terry Reedy tjreedy at
Wed Mar 3 21:18:26 CET 2010

On 3/3/2010 6:47 AM, Oren Elrad wrote:

> With that said, let me at least offer a token defense of my position.
> By way of motivation, I wrote that email after copying/pasting the
> following a few times around a project until I wrote it into def
> SilentlyDelete() and its cousin SilentlyRmdir()
> """ code involving somefile """
> try:
> ........os.remove(somefile)
> except:
> .......pass     # The bloody search indexer has got the file and I
> can't delete it. Nothing to be done.
> Certainly the parade of horribles (bad files! corrupt data! syntax
> errors!) is a tad melodramatic. Either os.remove() succeeds or it
> doesn't and the execution path (in the estimation of this programmer,
> at least) is not at all impacted by whether it succeeds or fails. I
> know with certainty at compile time what exceptions might be raised
> and what the consequences of passing them are and there is no sense
> pestering the user or sweating over it. Nor can I see the logic, as
> was suggested, in writing "except OSError:" since (seems to me) mere
> surplusage -- it neither causes a semantic difference in the way the
> program runs nor provides anything useful to the reader.

Suppose you misspell 'somefile' or 'remove' (or the file gets corrupted 
somehow -- which unfortunate can happen). Now you suppress the NameError 
or AttributeError, which is a mistake. Suppose someone copies your code 
into a context where 'os' is not imported or where 'os' is a variable 
(for bone type, for instance). More bad error suppression.

Bare excepts seem ok for experimental, draft, or throwaway code, but 
somewhat dubious for production code.

For anyone reading your code a few years from now, 'except OSError' 
would be clearer that that is all you mean to pass on.

Wrapping the code in a function makes the overhead of adding 'OSError' 
trivial. It also makes it trivial to do something different, like adding 
the file to a collection to be retried later. It also reduces the points 
of possible corruption to one instead of many.

Terry Jan Reedy

More information about the Python-list mailing list