[Tutor] Resuming one block of code continuously after exception in try/except construction
Alan Gauld
alan.gauld at btinternet.com
Mon Jul 7 01:28:24 CEST 2014
On 06/07/14 22:00, Ali Mammadov wrote:
> common pratice, I want my function to check user's input(in this case
> it's file name) and re-ask it again and again(until correct) offering
> him two choices: re-enter file name or close program.I've decided to use
> try/except construction in this particular task.
Thats the wrong solution.
try/except is for catching errors not repeating actions.
You need to combine the try/except with a loop.
> BTW, I created a small gist located here
> <https://gist.github.com/bca59570ea5fd365c672> which demonstrates my
> problem.
For short (<100lines) example just post it in your message, it saves a
lot of extra jumping around. Here it is:
---------------
def makelgpwdcombs(brutelistname):
try:
blst = open(brutelistname, 'r')
except:
print("[-] Invalid file name or insufficient priviliges")
else:
print("[+] File opened. Working...")
--------------------
Drop the else clause and put the try/except inside a while...
def makelgpwdcombs(brutelistname):
while True:
try:
blst = open(brutelistname, 'r')
break # exit loop if no error
except:
print("[-] Invalid file name or insufficient priviliges")
print("[+] File opened. Working...") # only after valid input
loops are for repeating, try/except is for catching errors.
Use the right tool for the job.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list