Except keyword

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.

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

print(tokens[5])

 

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:

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:

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.


Copyright 2024 © pythontic.com