[Python-3000] Exception re-raising woes
Mark Hammond
mhammond at skippinet.com.au
Sat May 31 08:43:43 CEST 2008
> >> This would render the following code illegal:
> >>
> >> def f():
> >> try: 1/0
> >> except: pass
> >> raise
> >
> > But you may want to use bare raise in a function called from an
> exception
> > handler, e.g.:
> >
> > def handle_exception():
> > if user() == "Albert":
> > # Albert likes his exceptions uncooked
> > raise
> > else:
> > logging.exception("an exception occurred")
> >
> > def f():
> > try:
> > raise KeyError
> > except:
> > handle_exception()
>
> This can be rewritten to use sys.exc_info(), ie:
>
> def handle_exception():
> if user() == "Albert":
> # Albert likes his exceptions uncooked
> raise sys.exc_info()[1]
> else:
> logging.exception("an exception occurred")
In both Python 2.x and 3 (a few months old build of Py3k though), the
traceback isn't the same. For Python 2.0 you could write it like:
def handle_exception():
...
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
Its not clear how that would be spelt in py3k though (and from what I can
see, sys.exc_info() itself has an uncertain future in py3k).
Cheers,
Mark
More information about the Python-3000
mailing list