Python Code To Ignore Errors
I have a code that stops running each time there is an error. Is there a way to add a code to the script which will ignore all errors and keep running the script until completion?
Solution 1:
You should always 'try' to open files. This way you can manage exceptions, if the file does not exist for example. Take a loot at Python Tutorial Exeption Handling
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
or
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
Do not(!) just 'pass' in the exception block. This will(!) make you fall on your face even harder.
Solution 2:
Where ever your error(s) is happening you can wrap it in a try/except block
for i in loop:
try:
code goes here...
except:
pass
Post a Comment for "Python Code To Ignore Errors"