Question

In my code below, it stops executing when I hit an exception. How can I get it to re-enter the try statement from where the exception left off? Maybe I am looking for a different way to tackle this without a try-except statement?

import requests
from requests import exceptions

contains_analyst = []

try:
    for x in data:
        r = requests.get(str(x), timeout=10, verify=False)

        if "analyst" in r.text:
            contains_analyst.append("Analyst")
            print "Analyst @ %s" % x
        else:
            contains_analyst.append("NOPERS")
            print "Nopers"

except exceptions.RequestException:
    contains_analyst.append("COULD NOT CONNECT") 
Was it helpful?

Solution

You should put the try/except around only the part whose error you want to trap. In your example, it looks like you want something more like this:

for x in data:
    try:
        r = requests.get(str(x), timeout=10, verify=False)
    except exceptions.RequestException:
        contains_analyst.append("COULD NOT CONNECT") 
    else:
        if "analyst" in r.text:
            contains_analyst.append("Analyst")
            print "Analyst @ %s" % x
        else:
            contains_analyst.append("NOPERS")
            print "Nopers"

Here I use the else clause of the try block to handle the case where no exception is raised (see documentation). In many cases, if you don't need to do anything else after the exception, you could just return at that point and put the following no-exception code in the main function body, reducing indentation a bit:

for x in data:
    try:
        r = requests.get(str(x), timeout=10, verify=False)
    except exceptions.RequestException:
        contains_analyst.append("COULD NOT CONNECT")
        return contains_analyst

    # execution reaches here if no exception
    if "analyst" in r.text:
        contains_analyst.append("Analyst")
        print "Analyst @ %s" % x
    else:
        contains_analyst.append("NOPERS")
        print "Nopers"

Of course, whether it makes sense to return at that point depends on the surrounding context of your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top