[Tutor] try & except
John Fouhy
john at fouhy.net
Tue Aug 8 23:11:02 CEST 2006
On 09/08/06, Magnus Wirström <asdlinux at yahoo.se> wrote:
> Hi
>
> 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
> biblioteket.","Säkerhetskopiering",wx.OK|wx.ICON_ERROR)
>
> (yeah ... it's swedish :) )
>
> 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. How can i make it
> retry to read the directory?
What logic are you looking for? Is it ---
"Try to read directory. If it doesn't work, try again. If it still
doesn't work, abort."
or ---
"Try to read directory. If it doesn't work, keep trying until it does."
In the former case, you could just put another try block in your except block:
try:
bibl=os.listdir("c:\\klientdata\\")
except:
wx.MessageBox("Kunde inte läsa käll
biblioteket.","Säkerhetskopiering",wx.OK|wx.ICON_ERROR)
try:
bibl=os.listdir("c:\\klientdata\\")
except:
wx.MessageBox("Kunde inte läsa käll
biblioteket.","Säkerhetskopiering",wx.OK|wx.ICON_ERROR)
In the latter case, you probably want some kind of loop:
success = False
while not success:
try:
bibl=os.listdir("c:\\klientdata\\")
success = True
except:
wx.MessageBox("Kunde inte läsa käll
biblioteket.","Säkerhetskopiering",wx.OK|wx.ICON_ERROR)
Of course, it would be nice to give the users another way out of the loop :-)
HTH!
--
John.
More information about the Tutor
mailing list