[Python] Exception handling: Differentiating between instances of the same error in Python

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    What is the recommended way of separately handling exceptions of the same type based on differences in what caused the exception?

    Let's say one desires to handle the following two instances of AttributeError differently:

    • 'str' object has no attribute 'append'
    • 'float' object has no attribute 'append'

    At the same time, we don't want to handle other attribute errors.

    Are there any generalizable answers that work for all exception types? Can I interrogate the exception object for details using some method or function on the exception object?

    Try:
    blah
    Except AttributeError as exc:
    if exc.baz('foo') is bar:
    handle 'str' object has no attribute 'append'
    elif plugh(exc):
    handle 'float' object has no attribute 'append'
    else:
    raise exc


    I assume that the obvious answer is to refactor. My question specifically regards the cases where that would be inefficient or simply not possible (if there are any such cases at all).

    Continue reading...

Compartilhe esta Página