I am trying to learn about exception handling in python by writing an International Space Station tracker in Python.
I have read https://docs.python.org/2/tutorial/errors.html and have found Handle errors with urllib2 useful, but I am struggling to understand how to have code continue to loop despite an exception being thrown and I'm not sure how to research this further.
I have this working code. It runs for days on my Raspberry Pi as part of a bigger program that makes a green light come on when ISS is overhead. Eventually though, an error is caused and the program halts. I'm looking for a way for the program to continue even if an error is called. I.e. This function is called every 10 seconds, but if there is an error I want the program to simply try again after 10 seconds while noting the error.
def issPosition(n):
try:
req = urllib2.Request("http://api.open-notify.org/iss-now.json")
response = urllib2.urlopen(req)
obj = json.loads(response.read())
if n == "lat":
return obj['iss_position']['latitude']
elif n == "long":
return obj['iss_position']['longitude']
except urllib2.HTTPError, e:
GPIO.output(24,True)
time.sleep(0.1)
GPIO.output(24,False)
print 'HTTPError = ' + str(e.code)
except urllib2.URLError, e:
GPIO.output(26,True)
time.sleep(0.1)
GPIO.output(26,False)
print 'URLError = ' + str(e.reason)
except httplib.HTTPException, e:
GPIO.output(26,True)
time.sleep(0.1)
GPIO.output(26,False)
print 'HTTPException'
except Exception:
GPIO.output(26,True)
time.sleep(0.1)
GPIO.output(26,False)
import traceback
print 'generic exception: ' + traceback.format_exc()
Pointers would be appreciated. Thank you.