Odds and Ends

Passing Optional Data

As we’ve seen, raise statements can pass an extra data item along with the exception for use in a handler. In general, the extra data allows you to send context information to a handler. In fact, every exception has the extra data; much like function results, it’s the special None object if nothing was passed explicitly. The following code illustrates:

myException = 'Error'              # string object

def raiser1():
    raise myException, "hello"     # raise, pass data

def raiser2():
    raise myException              # raise, None implied

def tryer(func):
    try:
        func()
    except myException, extraInfo:  # run func, catch exception + data
        print 'got this:', extraInfo

% python
>>> from helloexc import *
>>> tryer(raiser1)                  # gets explicitly passed extra data
got this: hello
>>> tryer(raiser2)              # gets None by default
got this: None

The assert Statement

As a special case, Python 1.5 introduced an assert statement, which is mostly syntactic shorthand for a raise. A statement of the form:

assert <test>, <data>          # the <data> part is optional

works like the following code:

if __debug__:
    if not <test>:
        raise AssertionError, <data>

but assert statements may be removed from the compiled program’s byte code if the -O command-line flag is used, thereby optimizing the program. Assertion-Error is a built-in exception, and the _ _debug__ flag is a built-in name which is automatically set to 1 unless the -O flag is used. Assertions are typically used to verify program conditions during development; when displayed, ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.