Re: FYI, an exception-handling trick

Tim Peters (tim@ksr.com)
Tue, 03 Mar 92 03:58:33 EST

> ... there USED to be an easy ( but not-documented, so not obvious )
> way - the sys module contained the objects sys.exc_type & sys.exc_value

Just noting that several of the library modules (e.g., lib/importall.py)
still reference these guys. I don't see them in sys either, although
they still show up in "strings" output ... hmm ... check this out!:

Python 0.9.4 alpha (>= Dec 24 1991).
Copyright 1990, 1991, 1992 Stichting Mathematisch Centrum, Amsterdam
>>> import sys
>>> dir(sys) # not there
['argv', 'exit', 'modules', 'path', 'ps1', 'ps2', 'stderr', 'stdin', 'stdout', 'version']
>>> oldsys = dir(sys)
>>> def newsys(): # return any new things that show up in sys.*
... ans = []
... for elt in dir(sys):
... if elt not in oldsys: ans.append(elt)
... return ans
...
>>> 1/0
Unhandled exception: ZeroDivisionError: integer division
Stack backtrace (innermost last):
File "<stdin>", line 1
>>> newsys() # hmm! more secret stuff for Steve <grin>
['last_traceback']
>>> def inner(): return 1/0
...
>>> def outer():
... try: return inner()
... except TypeError: pass
...
>>> outer()
Unhandled exception: ZeroDivisionError: integer division
Stack backtrace (innermost last):
File "<stdin>", line 1
File "<stdin>", line 2
File "<stdin>", line 1
>>> newsys() # voila!
['exc_traceback', 'exc_type', 'exc_value', 'last_traceback']
>>> sys.exc_type
'ZeroDivisionError'
>>> sys.exc_value
'integer division'
>>>

Haven't been able to get 'em to show up with anything simpler than that
(i.e., I seem to need to have at least one group of 'except' blocks
*not* catch the exception, and unwind at least one call level).

So they're there, but hard to guess when <grin>. Yo, Guido, feature or
bug? I didn't know about them before, so can't tell whether this is the
way they always worked. Offhand it sure looks like it would be more
pleasant/useful if they were set every time there's an exception ...

> ... One has to make an exhaustive list of exceptions, and any new
> ones not on the list will not be caught.

No argument from me, Steve -- seems to me that exception-handling gets
used when I have a very specific potential problem (in which case one or
two specific 'except' blocks do the trick), or when I have no idea what
might go wrong but don't want to crash regardless (in which case an
exhaustive list is just impossible to maintain as things change).

> ...
> [ Sorry Tim, but your kludge around it looks even uglier! :-( ]

as-a-long-time-fortran-programmer-i'm-immune-to-compliments<grin>-ly
y'rs - tim

Tim Peters Kendall Square Research Corp
tim@ksr.com, ksr!tim@uunet.uu.net