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:
- “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 outertry
block.