Confused again

Alex Martelli aleax at aleax.it
Mon Feb 24 13:11:56 EST 2003


Duncan Smith wrote:
   ...
> post a complete function.  If eg. "table =
> numtable1.margTo(numtable2.variables)" doesn't raise an exception I want
> to test "table" and "numtable2" for equality, and raise an exception if
> they
> aren't equal.  I can sort this out now, but I'd be interested to see any
> particularly elegant ways of getting the behaviour I'm after.  Cheers

I think "except:" (catching ANY exception) and the concept of
``elegant'' are somewhat incompatible -- you should have SOME
idea of what exceptions you expect and want to catch, rather
than blindly catching ALL of them (out of memory? processor has
caught fire? user is desperately banging on control-C to try
and kill the process?  You SURE you want to catch ALL of these?)

Anyway, apart from this important issue, this is a job for the
else cause of try/except.  I.e., where you now have:

>             try:
>                 table = numtable1.margTo(numtable2.variables)
>                 if table == numtable2:
>                     to_remove.append(table)
>                 else:
>                     raise 'An inconsistency in cluster %s' % str(self.id)
>             except:
>                 try:
>                     table = numtable2.margTo(numtable1.variables)
>                     if table == numtable1:
>                         to_remove.append(table)
>                     else:
>                         raise 'An inconsistency in cluster %s' %
> str(self.id)
>                 except:
>                     pass

and the raise, being within the try clause, is of course caught
by the immediately following except clause, you could have:

>             try:
>                 table = numtable1.margTo(numtable2.variables)
>             except:
>                 try:
>                     table = numtable2.margTo(numtable1.variables)
>                 except:
>                     pass
                  else:
>                     if table == numtable1:
>                         to_remove.append(table)
>                     else:
>                         raise 'An inconsistency in cluster %s' %
> str(self.id)
              else:
>                 if table == numtable2:
>                     to_remove.append(table)
>                 else:
>                     raise 'An inconsistency in cluster %s' % str(self.id)

IMHO you should also move to class-based exceptions (string ones
are a fossil, really!) as well as make the except: clauses more
specific, but this restructuring is THE key step to ensure your
raise statements DO something;-).


Alex





More information about the Python-list mailing list