try:
r = requests.get(url, params={'s': thing})
except requests.ConnectionError, e:
print e #should I also sys.exit(1) after this?
Is this correct? Is there a better way to structure this? Will this cover all my bases?
pythonpython-requestsrequest
try:
r = requests.get(url, params={'s': thing})
except requests.ConnectionError, e:
print e #should I also sys.exit(1) after this?
Is this correct? Is there a better way to structure this? Will this cover all my bases?
Best Answer
Have a look at the Requests exception docs. In short:
To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.
What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call
sys.exit
).You can either catch the base-class exception, which will handle all cases:
Or you can catch them separately and do different things.
As Christian pointed out:
An example:
Will print: