Bare Excepts

Jean-Michel Pichavant jeanmichel at sequans.com
Wed Dec 30 08:04:37 EST 2009


Victor Subervi wrote:
> Hi;
> I'll trouble-shoot bare excepts as I work on new code. I'll 
> trouble-shoot the others that don't (seem to) cause problems later. 
> Here's a new one:
>
>     for optionsStore, storeOptions in ourOptions().iteritems():
>       if store == optionsStore:
>         for option in storeOptions:
>           try:
>             fromForm = form.getfirst(option)
>             try:
>               fromForm, junk = string.split(fromForm, ':')
>             except:
>               pass # This is only an expedient to split options that 
> have a colon in them, such as the colors
>             fromForm = string.replace(fromForm, '-', '')
>             sql = 'select "%s" from %s%s t join %s p where p.ID=t.ID;' 
> % (fromForm, store, (option[0].upper() + option[1:]), store)
> #            print sql
>             cursor.execute(sql)
>             try:
>               optionsPrices += cursor.fetchone()[0]
>             except TypeError:
>               pass # There is no options price for this.
>           except:
>             raise
>  
> If there are no values entered into table (in this case 
> "productsSizes") for the given product ID, then "optionsPrices" should 
> not be added unto. Am I doing this correctly? Or is there a better way 
> than capturing ALL TypeErrors?
> TIA,
> beno
Hello,

Do not use the 'try except' clause when 'if then' can perfectly handle 
the case.

i.e.
            try:
              fromForm, junk = string.split(fromForm, ':')
            except:
              pass # This is only an expedient to split options that 
have a colon in them, such as the colors

would be better written

# This is only an expedient to split options that have a colon in them, 
such as the colors
if ':' in fromForm:
    fromForm, junk = fromForm.split(':')

or

fromForm = fromForm.split(':')[0]


Anyway, you should definitely use a coding rule checker, like pylint or 
pyckeck. It would sometimes point you into the correct direction. For 
instance, pylint will tell you that except: pass is often (not always) a 
clue for bad design/pattern and issue warnings for it.

In a more general manner, use try blocks when the code can throw 
exceptions upon condition you do not control. When you know about the 
conditions, use the if statement.

No:

a = None
try:
    a.split()
except AttributeError:
    pass


Yes:

a = None
if a:
    a.split()

Exception are required in the following example:

try:
    main()
except KeyboardInterrupt:
    print 'interrupted by user'

Cheers,

JM




More information about the Python-list mailing list