Re: FYI, an exception-handling trick

Steven D. Majewski (sdm7g@aemsun.med.Virginia.EDU)
Mon, 2 Mar 92 14:47:08 EST

tim@ksr.com>
>
> Maybe this is obvious to y'all, and apologies in advance if so. Wasn't
> obvious to me, and it seems like a pretty slick trick, so ...
>
> When writing a function that doesn't (or can't) trust its caller to have
> passed good stuff-- when they may have passed something that will cause
> an unpredictable exception, and it's not easy to check that in advance
> --I've been handling it like this:
>
> try:
> <dangerous code>
> except: # catch every possible goof
> print 'Unhappy with what you passed!'
> print 'But it\'s not my fault, it\'s yours!'
> print 'Wish I could tell you more, but I\'m too lazy to write'
> print 'an "except" clause for every possible problem.'
> raise UnhappyError
>
> What I really want here is some way to pass the original exception up to
> the caller, but to print my own msg first so that the user doesn't
> assume that the problem was caused by my code <grin>.
>

Well, 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,
so I used to be able to:

try:
<dangerous code>
except:
print my_msg
raise sys.exc_type,sys.exc_value

This WAS an undocumented feature, but it seems to have disappeared ( or
moved ? ). "import sys; dir(sys)" no longer shows exc_type & exc_value.

I was at first quite distressed to discover that this feature was now
missing. I know I'm looking for trouble relying on an undocumented
feature ... I don't mean I'm distressed because I have to change my
code. If it were moved and renamed, I wouldn't complain. [ As is is,
I'm trying to keep my complaint muted, because although I like the
functionality of the feature, I must admit it is sort of a kludge. It
might be better to have the exception be locally assignable as the
optional argument is, not a "global" symbol in module sys. ]
But now, it is quite awkward to write exception handlers that have
common code for several exceptions. (minor). AND I don't see any way
to write a generic exception handler that re-raises some of all of its
exceptions to an outer handler. (major). One has to make an exhaustive
list of exceptions, and any new ones not on the list will not be caught.

I see there are some notes about changes to error handling in error.c.
I assume that this change ( disappearance of sys.exc_type ) is related
to the changes in that code. (?)

My first impression is that I don't like this.
[ I admit I'm biased by growing up on VAX/VMS error handling, which
are a bit more "full featured" than vanilla C/UNIX signals. ]

- Steve

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