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

Christian Tanzer tanzer at swing.co.at
Sun Aug 26 09:51:48 CEST 2001


"Andrew Dalke" <dalke at dalkescientific.com> wrote:

> 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

Excuse my being lazy and just playing in the interpreter to see a few
errorcodes. For the purpose of a quick example that should be good
enough.

For production code you are right, of course.

> 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.

I didn't actually propose any changes to be done (although such
changes would improve Python, IMHO). This topic come up when somebody
asked whether to use exceptions or error codes...

I don't know what PyErr_SetFromErrno does but it might be enough to
change this one function/macro to switch to an exception hierarchy
without needing to change all the callers of PyErr_SetFromErrno.

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list