How to get out of a try/except inside a while? [Python]
You just break out of for
loop -- not while
loop:
running = True
while running:
for proxy in proxylist:
try:
h = urllib.urlopen(website, proxies = {'http': proxy}).readlines()
print 'worked %s' % proxy
running = False
except:
print 'error %s' % proxy
print 'done'
You can use a custom exception and then catch it:
exit_condition = False
try:
<some code ...>
if exit_conditon is True:
raise UnboundLocalError('My exit condition was met. Leaving try block')
<some code ...>
except UnboundLocalError, e:
print 'Here I got out of try with message %s' % e.message
pass
except Exception, e:
print 'Here is my initial exception'
finally:
print 'Here I do finally only if I want to'