Python except Keyword

Used with exceptions, what to do when an error occurs. The except keyword is used in conjunction with the try keyword and often the finally keyword. It lets you define a code block that handles exceptions.

Example

Python
try:
    result = 10 / 0
except:
    print("Oops - division by 0!")

Output

Oops - division by 0!

Specific exceptions can be caught as well.

Example

Python
def divide(n, d):
    try:
        result = n / d
    except ZeroDivisionError:
        # return positive infinity
        result = float('inf')
    return result

result = divide(10, 0)
print(result)

Output

inf

You can specify more than one exception type as well as the general exception handler at the end. For example:

Python
except SomeException:
    # handler
except SomeOtherException:
    # handler
except:
    # if anything else

Notes: Where to put the try and except handler is something to be carefully considered because the exception might occur deep inside nested functions, which means that the code has to have except handlers in possibly many places.

To capture the text of an exception, use this form:

Python
except Exception as e:
    # Log the message
    print(e)