[Tutor] subject screw [exception handling]
Kirk Bailey
deliberatus@my995internet.com
Wed, 26 Dec 2001 14:22:29 -0500
Thank you Danny, the script now reads:
#
# Let's extract the subject for later use!
#
try:
subject= string.strip(Message['Subject'])
except Keyerror:
subject="(none provided by sender)"
#
# The information is in the dictionary 'Message', each item keyed with
the
# header's name. The BODY of that dictionary is in the string 'msg'. So
are
# any attachments.
This ought to handle it, and when I come back with wife from registering
her car I will install it and test it. I will let the list know how it
works.
Danny Yoo wrote:
>
> 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!
--
Respectfully,
-Kirk D Bailey (C)2001
Addme! icq #27840081
end
Within the sweep of his sword, Each man is an Ubar.
http://www.howlermonkey.net/
http://www.sacredelectron.org/