[Python] How to handle cases where a list should always have one element (IndexError vs...

Discussão em 'Python' iniciado por Stack, Setembro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have a doubt about error handling design.

    Imagine you have code where you know a search should always return exactly one element and if it doesn't it shouldn't continue doing anything. In that case, it’s tempting to just write:

    result = my_list[0]


    The risk, of course, is that if the list is empty, it will raise an IndexError.

    In my situation, we use Sentry to capture these kinds of unhandled errors. When that happens, the end user does not see the traceback — instead, they just see a generic message telling them to contact our department, and we get the full error details in Sentry. So my question is:

    Should I leave the code as is (my_list[0]) and let Sentry catch the error if something unexpected happens?

    Or should I add explicit checks like this:

    if len(my_list) != 1:
    # Raise a business error (created by xml)


    The second approach would mean creating many extra user-facing errors for cases that, in principle, should never happen — cases that are more like bugs than valid business conditions.

    How do you usually handle this trade-off? Do you let Sentry handle unexpected errors (like IndexError), or do you prefer to explicitly raise controlled errors even for scenarios that “should never happen”?

    Continue reading...

Compartilhe esta Página