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

Exceptions are errors detected during runtime. It goes 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 except. An except clause is called “an exception handler”.

  • no “throw” – 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 you local library/exceptions.html#bltin-exceptions 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.