Search code examples
pythonexceptiontry-catchexcept

Difference between expect without specifier vs else?


In Python's try, except blocks, why does else need to exist if I can just use an except: without a specifier?


Solution

  • It seems like your understanding of how try, except, else, and finally is off.

    Here's a summary of how they all work together, from looking at https://docs.python.org/2/tutorial/errors.html:

    try:
        #Try something that might raise an exception
    except <exception specifier>:
        #Code here will only run if the exception that came up was the one specified
    except:
        #Except clause without specifier will catch all exceptions
    else:
        #Executed if try clause doesn't raise exception
        #You can only have this else here if you also have except blocks
    finally:
        #Runs no matter what