Some Python Examples
← prev | next →     Top-level ToC     /exceptions.html     (printable version)

Exceptions are errors detected during runtime. It 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 raise one yourself like so:

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

Notes:

  • no catch keyword. In Python it’s except. An except clause is called “an exception handler”.

  • no throw keyword. In Python it’s raise.

  • the finally blocks always runs: whether the exception was caught or not, or even whether or not there was an exception

  • See file:///home/john/opt/python-3.5.1-docs-html/library/exceptions.html#bltin-exceptions for the big list of built-in exceptions.

  • If you catch an exception but then don’t want to deal with it, you can re-raise it with simply raise.

  • If you catch the exception, then the code in your relevant except clause runs, the finally block runs (if there is one), and then things merrily go on.

  • If you don’t catch the exception, then after the finally block, the exception bubbles up to an outer try block.