[Python] Ordering of except statements in Python

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

  1. Stack

    Stack Membro Participativo

    If I have an inheritance hierarchy of exception classes, and in a try block if I want to attempt to handle a more specific (derived) exception before a more general one, do I just put the except statement for the derived class above the one for the base class?

    Is this how I would do it?

    class MyException(BaseException):
    pass

    class AnotherException(MyException):
    pass

    try:
    raise AnotherException()
    except AnotherException:
    print('Caught YetAnotherException!')
    except MyException:
    print('Caught MyException!')

    print('Done.')


    I have tried it out, and it works, but I'm surprised I am unable to find any documentation about this.

    Continue reading...

Compartilhe esta Página