Exceptions - Wed, Oct 30

Handling Errors

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.

Exceptions in Python

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.

Mastering Exceptions

Exceptions are objects -- classes with constructors and attributes! They enable non-local continuation of control.

If f calls g and g calls h, exceptions can shift control from h to f without waiting for g to return.

Exception handling tends to be slow.

Raising Exceptions

Assert Statements

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 optimized.

Raise Statements

Exceptions are raised with a raise statement: raise <expression>, where <expression> must evaluate to a subclass of BaseException or an instance of one.

Exceptions are constructed like any other object: TypeError('Bad argument!').

To catch all errors, use RuntimeError.

Handling Exceptions with Try Statements

try:
    """try suite"""
except <exception> as <name>:
    """except suite"""

The """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.