except keyword

The except key word marks an exception handler for one of the exceptions a try block is enclosed for. After handling an exception, program continues after the try block.

Keywords Updated 21 May 2019 2 min read

The exception handling mechanism in Python is provided through the keywords try, except, finally and raise.

While the try keyword marks a block of Python code which may generate one or more exceptions during its run time, the except keyword marks a block of Python code as one of the handlers of those exceptions. These except handlers are searched from the inner scope to the outer scope. When a matching exception handler is found, it is executed and the program execution continues after the try block. If a matching exception handler is not found, then the program exits after printing the traceback.

Example

The following Python code accesses an invalid index from a Python list which raises an exception IndexError. Since the code block is not enclosed by a try block and there are no except handlers, the program exits after printing the traceback.

python
tokens = ["try", "catch", "except", "finally", "from"];

print(tokens[5])

Output

Output
Traceback (most recent call last):

  File "ex_ex.py", line 3, in <module>

    print(tokens[5])

IndexError: list index out of range

Example

The Python code example below acesses a tuple of tokens with an invalid index, which raises an exception - IndexError:tuple index out of range. Since the code is enclosed by try block and an associated except block, the program handles the exception and continues after the try block.

Example

python
tokens = ("and", "or", "not");

def getToken(token):

    try:

        return tokens[token]

    except Exception as Ex:

        print("Exception:%s"%Ex)

tokenIndex  = 4

token       = getToken(tokenIndex)

print("Token: %s"%(token))

tokenIndex = 2

token       = getToken(tokenIndex)

print("Token: %s"%(token))

Output

Output
Exception:tuple index out of range

Token: None

Token: not

Note the token value None in the second line of output which corresponds to the invalid tuple index.