[Tutor] IOError exception handling

Allyn Weaks allyn.@tardigrade.net
Mon, 29 Jul 2002 02:02:21 -0700


On 28/7/02, Danny Yoo wrote:
"Sean 'Shaleh' Perry" <shalehperry@attbi.com> wrote

>> As you can see, IOError covers many issues
>>
>> >>> try:
>> ...   fd = open('/home/shoon/xinitrc')
>> ... except IOError, e:
>> ...   print e[0], e[1]
>> ...
>> 13 Permission denied
>>
>> I am sure there is a wrapper for errno somewhere in python.
>
>Here you go:
>
>    http://www.python.org/doc/lib/module-errno.html

Many thanks.  Betwixt the two of you, I've now got:

def errortest():
    try:
        fd = open(filename)
        text = fd.readlines()
        return len(text)
    except IOError, e:
        if e[0] == 2: return 0  # file not found
        print e                 # any other error
        sys.exit(1)

Which works when I force errors of several types.  Do I need the
sys.exit(1), and is 1 a reasonable generic number?  I've seen it in
several examples, and since I'm still partly in monkey-see, monkey-do
mode, I stuck it in even though it superficially works without it. :-)
-- 
Allyn Weaks    allyn@tardigrade.net   Seattle, WA  Sunset zone 5
Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/
"The benefit of even limited monopolies is too doubtful, to be opposed
to that of their general suppression."  Thomas Jefferson