[Python-Dev] Chained Exceptions
James Y Knight
foom at fuhm.net
Fri May 13 03:56:21 CEST 2005
On May 12, 2005, at 6:32 PM, Ka-Ping Yee wrote:
> Suppose exceptions have an optional "context" attribute, which is
> set when the exception is raised in the context of handling another
> exception. Thus:
>
> def a():
> try:
> raise AError
> except:
> raise BError
>
> yields an exception which is an instance of BError. This instance
> would have as its "context" attribute an instance of AError.
>
I think it's a bad idea to have this happen automatically. Many times
if an exception is raised in the except clause, that doesn't
necessarily imply it's related to the original exception. It just
means there's a bug in the exception handler.
Take the divide by 0 example:
try:
doABunchOfStuff()
except:
1/0
If you're going to do anything useful with the chained exception
information (such as have it printed by the default exception
printer), it'd be best to not print a bunch of irrelevant backtraces
for all exceptions up the stack. The reason that doABunchOfStuff
failed is not important. What is important is only that you had a
divide by 0.
In my mind it's much better to be explicit about your intentions, via
something like:
try:
raise AError
except Raiseable, e:
raise BError(cause=e)
Of course you can already do similar with current python, it just
can't be spelled as nicely, and the default traceback printer won't
use the info:
try:
raise AError
except:
newException = BError()
newException.cause=sys.exc_info()
raise newException
James
More information about the Python-Dev
mailing list