else in try/except

Robert Kern robert.kern at gmail.com
Tue Nov 15 10:06:15 EST 2011


On 11/15/11 2:31 PM, Grant Edwards wrote:
> On 2011-11-15, Barry W Brown<brownbar at gmail.com>  wrote:
>
>> I thought that the point of the else clause is that it is reached
>> only if there is no exception in the try clause.
>
> Not really.  If that's all you wanted, then you just put the code at
> the end of the try block.

No, he's right. You should only put code in the try: block where you want 
exceptions to be caught. Everything else should be outside of the block. You 
really do want to minimize the amount of code inside the try: block.

try:
     # minimal code that might raise exceptions that you want to catch
except ThisError:
     # handle ThisError exceptions, and probably continue execution
except ThatError:
     # handle ThatError exceptions, and probably continue execution
else:
     # Code that only runs if ThisError or ThatError were not
     # raised in the try: block. This code may raise ThisError or ThatError
     # exceptions that should not be caught by the above except: blocks.

# Other code that runs regardless if a caught-and-continued exception
# was raised or not

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list