Sometimes, computer programs behave in non-standard ways:
Exceptions are a built-in mechanism in a programming langauge to declare and respond to exceptional conditions.
Python raises an exception whenever an error occurs. Exceptions can be handled by the program, preventing the interpreter from halting.
Unhandled exceptions will cause Python to halt execution and print a stack trace.
Exceptions are objects -- classes with constructors and attributes! They enable non-local continuation of control.
h, exceptions can shift control from
f without waiting for
g to return.
Exception handling tends to be slow.
Assert statements raise an AssertionError:
assert <expression>, <string>. Assertions are designed to be used liberally. They can be ignored for efficiency by running Python with the
-O flag. The
-O flag stands for
Exceptions are raised with a
raise <expression>, where
<expression> must evaluate to a subclass of BaseException or an instance of one.
Exceptions are constructed like any other object:
To catch all errors, use
try: """try suite""" except <exception> as <name>: """except suite"""
"""try suite""" is executed first. If, during the execution, an exception is raised that is not otherwise handled, if the class of the exception inherits from
<exception>, then the
"""except suite""" is executed, with
<name> bound to the exception. Then, the remainder of the
"""try suite""" is executed.