Why does list.index throw an exception, instead of using an arbitrary value (for example, -1
)? What\'s the idea behind this?
To me it looks cleaner to d
The "exception-vs-error value" debate is partly about code clarity. Consider code with an error value:
idx = sequence.index(x)
if idx == ERROR:
# do error processing
else:
print '%s occurred at position %s.' % (x, idx)
The error handling ends up stuffed in the middle of our algorithm, obscuring program flow. On the other hand:
try:
idx = sequence.index(x)
print '%s occurred at position %s.' % (x, idx)
except IndexError:
# do error processing
In this case, the amount of code is effectively the same, but the main algorithm is unbroken by error handling.