Usually the way its done in Python (or the way I've done it) is to use simply use the variable as a list, then handle the error. This can be done with try...except
block as show below:
def tryExceptExample(data):
try:
for a in data: #or whatever code you want to run
print a
except TypeError:
print "Invalid data" #code you want to run if code in try block fails
finally:
print "fin" #optional branch which always runs
Sample Output:
>>> tryExceptExample([1,2,3])
1
2
3
fin
>>> tryExceptExample("abcd")
a
b
c
d
fin
>>> tryExceptExample(5)
Invalid data
fin
Some Things to Note:
The code in the try
branch will run until it hits an error, then immediatly proceed to except
, meaning all lines before an error execute. For this reason, try to keep the number of lines in this branch to a minimum
Here the except
branch is shown with a TypeError
. This means only TypeErrors
will be "caught" by this branch and any other errors will be thrown normally. You can have as many except
branches as needed for as many errors as you want to catch. You can also have a "bare" except
branch which will catch all errors, but this is considered poor form and non-pythonic