[Python] How can I catch multiple exceptions in one line? (in the "except" block)

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

  1. Stack

    Stack Membro Participativo

    I know that I can do:

    try:
    # do something that may fail
    except:
    # do this if ANYTHING goes wrong


    I can also do this:

    try:
    # do something that may fail
    except IDontLikeYouException:
    # say please
    except YouAreTooShortException:
    # stand on a ladder


    But if I want to do the same thing inside two different exceptions, the best I can think of right now is to do this:

    try:
    # do something that may fail
    except IDontLikeYouException:
    # say please
    except YouAreBeingMeanException:
    # say please


    Is there a way that I can do something like this (since the action to take in both exceptions is to say please):

    try:
    # do something that may fail
    except IDontLikeYouException, YouAreBeingMeanException:
    # say please


    Now this really won't work, as it matches the syntax for:

    try:
    # do something that may fail
    except Exception, e:
    # say please


    So, my effort to catch the two distinct exceptions doesn't exactly come through.

    Is there a way to do this?

    Continue reading...

Compartilhe esta Página