MC logo
Exceptions I
[^] Code Examples

# Python exception handling.

# Choose two random integers.
import random
i = random.randrange(0, 8)
j = random.randrange(-1, 6)
print(i, j)

# Get a nice little array, then try a bunch of dangerous stuff.
some = [3, 10, 0, 8, 18];
    # We try to execute this block.
    den = some[j] / i
    print("A:", den)
    frac = (i + j) / den
    print("B:", frac)
    if frac < 2:
        k = 3
        k = 'mike'
    print("C:", k)
    print("D:", some[k])
# This is the catch block.
except ZeroDivisionError:
    print("\nDivision by zero.")
except TypeError as terr:
    # The detail provides extra information about the exception.
    print("\nSome type mismatch:", terr)
except IndexError as ndxerr:
    print("\nSome value is out of range:", ndxerr)
    # Except without an exception name catches any exception.
    print("\nSomething else went wrong.")

# An else attached to an except block is run if no exception occurrs.
    print("\nThat's odd, nothing went wrong.")

Python has an exception mechanism similar to Java. Exceptions are classes derived from Exception. The try/catch construct becomes try/except, and uses Python's indent grouping.

This example catches several built-in exceptions. User-defined exceptions are quite possible, but we won't do that just yet.

Some exceptions provide an argument which describes it in more detail. Whether this exists, or what exactly it looks like, depends on the exception.