Jimbo Mombasa
Jimbo Mombasa

Reputation: 528

How to continue python script loop even though IOError?

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

Answers (5)

Adniel
Adniel

Reputation: 16

Or why not:

with ignored(IOError):
    <code that can fail>

Upvotes: 0

joaquin
joaquin

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

Mp0int
Mp0int

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-exceptblock 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

drrlvn
drrlvn

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.

The longer explanation:

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

Simpleton
Simpleton

Reputation: 797

Try this:

try:
    <do something - you code here>
except IOError: pass

Upvotes: 0

Related Questions