I want to exception handle 'list index out of range.'
Solution 1:
Handling the exception is the way to go:
try:
gotdata = dlist[1]
except IndexError:
gotdata = 'null'
Of course you could also check the len()
of dlist
; but handling the exception is more intuitive.
Solution 2:
You have two options; either handle the exception or test the length:
if len(dlist) > 1:
newlist.append(dlist[1])
continue
or
try:
newlist.append(dlist[1])
except IndexError:
pass
continue
Use the first if there often is no second item, the second if there sometimes is no second item.
Solution 3:
A ternary will suffice. change:
gotdata = dlist[1]
to
gotdata = dlist[1] if len(dlist) > 1 else 'null'
this is a shorter way of expressing
if len(dlist) > 1:
gotdata = dlist[1]
else:
gotdata = 'null'
Solution 4:
For anyone interested in a shorter way:
gotdata = len(dlist)>1 and dlist[1] or 'null'
But for best performance, I suggest using False
instead of 'null'
, then a one line test will suffice:
gotdata = len(dlist)>1 and dlist[1]
Solution 5:
Taking reference of ThiefMaster♦ sometimes we get an error with value given as '\n' or null and perform for that required to handle ValueError:
Handling the exception is the way to go
try:
gotdata = dlist[1]
except (IndexError, ValueError):
gotdata = 'null'