There is no way to clear the "current" exception, which is
available via the sys.exc_info() function. There are a few
(obscure) easons why one would want to be able to do so,
and mainly due to the implementation details of how
exception information is stored.
Specifically, sys.exc_info() will return information
on the last
exception even outside of an 'except:' block that
caught the
exception. So an exception and all of the frame
objects on the
stack, and all local variables stored in those frames
are kept
alive in the last exception traceback until either 1)
another
exception is thrown, or 2) the stack returns to a frame
that is
handling another exception (thrown before the "current"
exception).
Thus, it is sometimes useful to be able to clear the
"current"
exception. e.g.:
1) Some error handling and logging handlers will report
on the current or last exception (as a hint about
what may
have gone wrong). Once that information is handled,
additional error handling or logging calls should
not report
it again.
2) Sometimes resources are not released when an exception
is raised until the next exception is raised.
This causes
problems for programs that rely on object
finalization to
release resources (like memory, locks, file
descriptors, etc.).
Such code is suboptimal, but it exists and there
are few
easy alternatives other than creating many
'finally:' clauses
(which can violate encapsulation and abstraction layer
boundries and is syntactically hairy at times).
Anyhow,
such programs may want to clear the current exception
and trigger garbage collection at certain
synchronization
points, in order to flush pending object
finalization. Clearly,
this is a somewhat hit-or-miss strategy, though it
works
fairly well on practice, though no sane developer
should
ever rely on it.
Anyhow, I've implemented a trivial patch to sysmodule.c
to add a 'exc_clear()' function that clears the current
or last exception. I've also added a test case and
updated the documentation.
|