[Tutor] try & except

Alan Gauld alan.gauld at freenet.co.uk
Tue Aug 8 23:29:10 CEST 2006


> I'm playing around with try: and except: i have a code like this
>        try:
>            bibl=os.listdir("c:\\klientdata\\")
>        except:
>            wx.MessageBox("Kunde inte läsa käll ...
>
> So far i get how to use it but i would like to be able to execute 
> the try block again after it jumped to the exception.

Yes, thats a common desire, unfortunately it isn't possible,
at least not directly.

One way round this is to put the try inside a function then
call the function inside an outer try, like this:

def mylistdir(d):
     try:   bibl = os.listdir(d)
     except: raise

try:
    mylistdir("C:\\....")
except:
    print 'oops!'
    mylistdir(default)

But even here you only get wo bites at the pie.

If you need more you need to write a loop:

success = False
while not success
      try:
            mylistdir(d)
            success = True
      except: print 'oops!'


But I agree a retry option would be nice. But I've never found a
language yet that supports it. (There are some good reasons why
this is the case BTW, to do with the uncertain state of the code
block that you exit.)

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



More information about the Tutor mailing list