[Tutor] subject screw [exception handling]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 26 Dec 2001 11:06:52 -0800 (PST)


On Wed, 26 Dec 2001, Kirk Bailey wrote:

> Discovered this when testing TLpost. SOME letters came through, some
> did not. The bombes, had no subject field. SO I sent a letter to an
> alias to save the incoming letter as a file, and ran the script
> locally, redirecting input from the file. This way I could watch error
> messages on the console screen. Very informative, I got back:
>
> ns# ./TLpost.py testlist3 < testfile
> Traceback (innermost last):
>   File "./TLpost.py", line 159, in ?
>     subject= string.strip(Message['Subject'])
>   File "/usr/local/lib/python1.5/rfc822.py", line 356, in __getitem__
>     return self.dict[string.lower(name)]
> KeyError: subject
> ------------------------------------------------------------------------
>
> Apparently when there is NO subject, no kidding we really mean it, it
> omits this header. When rfc822 receives such a leter, it screws the
> pooch and crashes, albeit politely.

Right; the designers of rfc822 felt that missing a header like this
should be a serious error, so that's why we're seeing the KeyError.

To recover gracefully from this, we can use "exception handling".  On your
line:

    subject = string.strip(Message['Subject'])

we can place an "exception handler" to take care of wacky situations (such
as missing Subject lines):


###
    try:
        subject = string.strip(Message['Subject'])
    except KeyError:
        subject = ''
###

which says something like: "Try to assign 'subject' that message headers.  
On the exceptional circumstance of a KeyError, assign 'subject' to the
empty string instead."


It might be good to write a function that automates this exception
handling for us when we grab at headers:


###
def getHeader(msg, header_name):
    try:
        header = string.strip(msg[header_name])
    except KeyError:
        header = ''
    return header
###

This getHeader() function then guarantees that we'll at least get an empty
string out of the situation.


The Python tutorial gives some good information on the idea of exceptions:

    http://python.org/doc/current/tut/node10.html


Good luck to you!