How to use sys.exc_info()???

Donn Cave donn at u.washington.edu
Wed Oct 18 18:12:35 EDT 2000


Quoth "Alex Martelli" <aleaxit at yahoo.com>:
| "Roy Smith" <roy at panix.com> wrote in message
| news:8sksit$mj1$1 at panix6.panix.com...
|     [snip]
|> try:
|>      open ('xxx')
|> except:
|>      foo = sys.exc_info()
|>
|> What I end up with in foo is
|>
|> (<class exceptions.IOError at 80a7e20>, <exceptions.IOError instance at
|80c82d0>, <traceback object at 80c92c8>)
|>
|> What I don't understand is how to go from the 3-tuple I get back from
|> exc_info() to the string "No such file or directory"?
|
| >>> try: open('xxx')
|     except: foo=sys.exc_info()
|
| >>> foo
| (<class exceptions.IOError at 00805E0C>, <exceptions.IOError instance at
| 00B303FC>, <traceback object at 00B35E80>)
| >>> foo[1]
| <exceptions.IOError instance at 00B303FC>
| >>> dir(foo[1])
| ['args', 'errno', 'filename', 'strerror']
| >>> foo[1].args
| (2, 'No such file or directory')
| >>> foo[1].errno
| 2
| >>> foo[1].filename
| 'xxx'
| >>> foo[1].strerror
| 'No such file or directory'
| >>>
|
| So, specifically, what you want is foo[1].strerror, but there's other
| info in the foo[1] instance which you may want to access (and if
| you're just testing to see if the specific error is such-and-such,
| foo[1].errno may be handier).

And, again depending on the application, perhaps:

 >>> str(foo[1])
 "[Errno -2147459069] No such file or directory: 'xxx'"

The nice thing about that is you don't need to know about the internals
of the particular exception class, str() works with anything.  I hate it
when an exception handler blows up trying to puzzle out its exception.

Also note the errno - that value (also in foo[1].errno) is what I get
on BeOS.  It's errno.ENOENT just as would be the case on UNIX, but
obviously it's not 2.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list