Reputation: 528
I have a program which request info from the twitter API, and from time to time I get an error:
IOError: [Errno socket error] [Errno 54] Connection reset by peer
I want to know how can I keep my script running (looping). I know that this has something to do with:
try:
except IOError:
but I can not figure it out.
Upvotes: 1
Views: 17885
Reputation: 85603
The simpler structure is like this:
my_while_or_for_loop:
some_code_here_maybe
try:
my_code_or_function_that_sometimes_fails()
except IOError:
pass # or some code to clean things that went wrong or to log the failure
some_more_code_here_maybe
You want to read the docs
The full construction can be more complex and includes try/except/else/finally
.
From an example in docs:
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print "division by zero!"
... else:
... print "result is", result
... finally:
... print "executing finally clause"
Upvotes: 6
Reputation: 18727
Here is is documentationabout exceptions...
Simply, if a code block have possibility to cause some known errors (like input output error) in some conditions, you define an try-except
block to handle such errors. That will make your script keep runnung and let you execute diffrent code blocks according to diffrent error status.... Like:
try:
<do something>
except IOError:
<an input-output error occured, do this...>
except ValueError:
<we got something diffrent then we expected, do something diffrent>
except LookupError:
pass # we do not need to handle this one, so just kkeep going...
except:
<some diffrent error occured, do somethnig more diffrent>
If you simply do nothing and continue, you can use pass
, like:
try:
<do something>
except:
pass
Upvotes: 2
Reputation: 8437
The part you're missing is pass
. That is a simple no-op expression, which exists because Python can have no empty blocks.
What you need to do is to catch the IOError exception being thrown, and ignore it (possibly logging it and such) using pass
.
To do that you need to wrap the code that can fail in a try
and except
block, like this:
try:
<code that can fail>
except IOError:
pass
What this does is explicitly ignore IOErrors, while not ignoring others. If you want to ignore all exceptions, simply remove the IOError
part so the line says except:
.
You should really read the Python tutorial, specifically the section about error handling.
Upvotes: 1
Reputation: 797
Try this:
try:
<do something - you code here>
except IOError: pass
Upvotes: 0