# Python exception handling.
# Choose two random integers.
i = random.randrange(0, 8)
j = random.randrange(-1, 6)
# 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
frac = (i + j) / den
if frac < 2:
k = 3
k = 'mike'
# This is the catch block.
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
Some exceptions provide an argument which describes it in more
detail. Whether this exists, or what exactly it looks like,
depends on the exception.