[Tutor] Script performance: Filtering email

alan.gauld@bt.com alan.gauld@bt.com
Wed, 17 Jan 2001 10:26:05 -0000


> I have a question, about try/except blocks in general.
> (I am assuming they come in pairs, like if/else, right?)

Correct, they are almost identical to C++ try/catch pairs.
(ISTR YOu have a C++ background?)
 
> If I put
> 
> try:
>     (body of my script)
> 
> and suppose the script tries to connect to the SMTP server, 
> but fails, will it try more than once? 

Only if you code it so. The try simply says "try executing 
this sequence of instructions and see what happens" ie once thru'.

If the block of code raises an exception - either explicitly 
or because a function it calls does so internally - it will jump 
to the except part. If the specific exception is caught it will 
execute that handler otherwise it will percolate up thru' any 
outer except statements till it reaches the global system 
handler which will generate the familiar python stack trace etc.


> it raised an error, how would I keep the script running and 
> trying to connect to that server later?

use a loop with a timer/sleep inside. Test for success of 
the connection to break out of the loop. eg to do 3 retries:

try:
  for attempt in range(4):
    # connect to service
    # if successful: break
    # else sleep 
except:
  print "failed to connect after 4 attempts"

Now if your connect mechanism raises exceptions on failure instead of
retirning error codes you simply nest try statements:

try:
  for attempt in range(4):
    try:
       # connect to service
       break
    except: # sleep 
except:
  print "failed to connect after 4 attempts"
    
HTH,

Alan G.