How to name Exceptions that aren't Errors

Scott David Daniels Scott.Daniels at Acm.Org
Fri Apr 8 12:18:55 EDT 2005


Leif K-Brooks wrote:
> Steve Holden wrote:
> 
>> I've even used an exception called Continue to overcome an irksome
>> restriction in the language (you used not to be able to continue a
>> loop from an except clause).
> 
> 
> Out of curiosity, how could you use an exception to do that? I would 
> think you would need to catch it and then use "continue", which wouldn't 
> be possible because of the restriction you were trying to work around in 
> the first place.

Here is a stupid way to calculate a 3-element median:

     class Success(Exception): pass

     def median_if_sorted(x,y,z):
         if x >= y >= z:
             raise Success(y)
     def median(a, b, c):
         try:
             median_if_sorted(a, b, c)
             median_if_sorted(c, b, a)
             median_if_sorted(a, c, b)
             median_if_sorted(c, a, b)
             median_if_sorted(b, a, c)
             median_if_sorted(b, c, a)
         except Success, instance:
             result, = instance.args
             return result
         else:
             raise ValueError, 'Nothing found'

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list