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

Exceptions are errors detected during runtime. They go like:

    # 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:
    # ...
    # Optional. For code that must be executed if no exceptions
    # are raised.
    print('always executed')

And raise one yourself like so:

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


  • no “catch” – in Python it’s called except. An except clause is called “an exception handler”.
  • no “throw” – in Python it’s called raise.
  • the finally blocks always runs: whether the exception was caught or not, or even whether or not there was an exception
  • See your local file:///home/john/opt/python-3.6.4-docs-html/library/exceptions.html doc 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.