Using Try/Except statement in Python
Question: my code is as follows:

    
    
    import mechanize 
    import urlparse
    import util 
    
    url = "https://math.berkeley.edu/~strain/"
    urls = [url]
    visited = []
    link_pdf = []
    br = mechanize.Browser()
    br.open(url)
    while len(urls) > 0: 
        try:
            br.open(urls[0])
            urls.pop(0)
            for link in br.links(): 
               new_url = urlparse.urljoin(link.base_url, link.url)
               print new_url
               urls.append(new_url) 
        except: 
             print "error"
    

Below is how it runs: At some points, it will be like this:

    
    
    https://math.berkeley.edu/~strain/Publications/tvm.pdf
    error
    https://math.berkeley.edu/~strain/Publications/vce.pdf
    error
    https://math.berkeley.edu/~strain/Publications/mclaughlin.strain.kdv.pdf
    error
    error
    error
    error
    error
    error 
    ....
    

And I only want it print out four times

It will run and print "error" until some points that it will only print out
error forever. And, I only want it hit my script hit error only four time and
break it. hence, can anyone show me how to do it? Thank you.

EDIT: I posted the the code that cause error forever and how it runs.


Answer: If I am understanding your question correctly, you want to allow for an error
only four times.

Count the number of errors you have had and let the loop end when you hit the
limit.

    
    
    errors = 0
    while len(urls) > 0 and errors < 4:
        try:
            #doing something 
        except:
            errors += 1
            print "error"
    

