Python Notes and Examples

Exceptions

Exceptions are errors detected during runtime. Catching them goes like:

try:
    dangerous_stuff()
    # If that raises an exception, no more of the try clause is
    # executed --- we go straight to looking for a handler.
    print('may not make it here')
except ZeroDivisionError as e:
    # do something with `e` or `e.value`
except NameError:
    # ...
except TypeError:
    # ...
else:
    # Optional. For code that must be executed if no exceptions
    # are raised.
finally:
    print('always executed')

And throw one yourself like so:

raise NameError('Not happy with the name!')

Note Python’s peculiar terminology:

Also: