[Tutor] how to catch particular Errno for Exceptions

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Apr 5 21:32:27 EDT 2004



On Mon, 5 Apr 2004, Brian van den Broek wrote:

> how do I catch a specific Errno for an exception?
>
> I have no G: drive and have tried the following code:
>
> import os
>
> try:
>      os.mkdir('g:\\silly')
> except OSError:
>      print 'OSError caught!'
>
> try:
>      os.mkdir('gGg:\\sillier')
> except OSError, (2,):  #what to write here?
>      print 'OSError Errno 2 caught!'


Hi Brian,


According to the library documentation on the builtin exceptions:

    http://www.python.org/doc/lib/module-exceptions.html

we can take the exception instance, and look at its 'errno' attribute
value.  For example:

###
>>> try:
...     os.mkdir("/g/silly")
... except OSError, e:
...     print e.errno, e.strerror
...
2 No such file or directory
###


We capture the exception instance in a name called 'e', and then we can
access the individual fields in 'e' to get a more specific reason why
things are broken.


But how do we know what error code number 2 means?  That's when we want to
look at the 'errno' module:

    http://www.python.org/doc/lib/module-errno.html

###
>>> import errno
>>> errno.errorcode[2]
'ENOENT'
###


So in your block of code that tests for the error type, you may want to
avoid hardcoding the number '2', and instead use the symbolic error code
name errno.ENOENT.


Hope this helps!





More information about the Tutor mailing list