Search code examples
pythonurlopen

Is there a way to prevent the "bad connection" or "no network" error inside python?


I use urlopen command from urllib.request package and it works properly.

But because it is inside an infinite loop I want to consider the possible "No network" Conditions. I do not want my code to break down because of this error.

I tried the function below but it does not work:

def update():
    try:
        cmd = 'getUpdates'
        resp = urlopen(URL + cmd)
        line = aux_dec2utf8(resp)
        upds = json.loads(line)
        NoM = len(upds['result'])
    except ValueError:
        print('NO NETWORK')    
    return NoM, upds

Error Image


Solution

  • I think the issue here is the ValueError exception. You may want to set up an exception for urllib.HTTPError and/or urllib.URLError to catch the error you’re attempting to keep from breaking your script.

    ValueError is used to catch an invalid argument and may not be what’s killing the flow.