Python Notes and Examples

Exceptions

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

And throw one yourself like so:

Note Python’s peculiar terminology:

  • “catch” in Python is spelled “except
  • “throw” in Python is spelled “raise

Also:

  • An except clause is called “an exception handler”.
  • the finally block always runs: whether the exception was caught or not, or even whether or not there was an exception
  • See your local Exception doc for the big list of built-in exceptions, including the inheritance hierarchy.
  • If you catch an exception but then can’t/won’t 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.