When to use exceptions (was Re: reducing if statements...)

Andrew Dalke dalke at dalkescientific.com
Fri Aug 24 11:22:03 EDT 2001


tanzer at swing.co.at wrote:
>    IO_Exception_Map  = { 2 : NoSuchFile
>                        , ...
>                        , 13 : PermissionDenied
>                        , ...
>                        , 20 : NotADirectory
>                        }

This isn't correct.  You can't use 2 and expect that to be
the right number.  You need to use errno.ENOENT instead of 2 since
it may be different on different machines.  Quoting from
errnomodule.c

] The value of each symbol is the corresponding integer value,
] e.g., on most systems, errno.ENOENT equals the integer 2.

and the implementation is

] #ifdef ENOENT
]         inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory");
] #endif


The list of error codes in errnomodule.c is ...

        /*
         * The names and comments are borrowed from linux/include/errno.h,
         * which should be pretty all-inclusive
         */

which means it doesn't necessarily include error codes from different OSes.
But the .get() would work around that.

> I can't follow. The IO_Exception_Map could still map ETXTBSY to
> TextBusy -- that this exception isn't raised on a specific system
> shouldn't be a problem for anybody, should it?

Ahh, my concern was that if a platform doesn't have a given errno
then there shouldn't be an exception defined for it.  But there's
no need for that.


But my point probably boils down to that the C errno interface
doesn't have a discovery process to figure out all the error numbers
that are supported, and the exception values and meanings may differ on
different platforms, so it's complicated to make things occur the
way you want them to.

It can be done, but is the complexity worth it?  I've never needed
to be that precise in any of my code, so I'm not going to spend
any more time worrying about this.

Also, looking through the Python code, there's a lot of places which
put the errno into the exception, not just IOError

PyErr_SetFromErrno(BsddbError);
PyErr_SetFromErrno(CdError);
PyErr_SetFromErrno(DbmError);
PyErr_SetFromErrno(ImgfileError);
PyErr_SetFromErrno(LinuxAudioError);
PyErr_SetFromErrno(PyExc_IOError);
PyErr_SetFromErrno(PyExc_RuntimeError);
PyErr_SetFromErrno(PyExc_ValueError);
PyErr_SetFromErrno(PySocket_Error);
PyErr_SetFromErrno(ResourceError);
PyErr_SetFromErrno(SelectError);
PyErr_SetFromErrno(SunAudioError);
PyErr_SetFromErrno(mmap_module_error);
PyErr_SetFromErrnoWithFilename(LinuxAudioError,
PyErr_SetFromErrnoWithFilename(SunAudioError,

so quite a bit of the code may need to be changed.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list