Python list.index throws exception when index not found

前端 未结 10 1027
抹茶落季
抹茶落季 2020-12-09 17:00

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

10条回答
  •  离开以前
    2020-12-09 17:30

    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.

提交回复
热议问题