try except inside exec

Aaron Brady castironpi at
Fri May 29 20:25:13 CEST 2009

On May 29, 9:55 am, Michele Petrazzo
<michele.petrazzo at> wrote:
> Aaron Brady wrote:
> > STR = """
> > class Globals:
> >    err = 0
> > def a_funct():
> >    try:
> >       1/0
> >    except ZeroDivisionError:
> >       import traceback
> >       Globals.err = traceback.format_exc()
> > """
> > exec STR in env
> > try:
> >   env["a_funct"]()
> > except ZeroDivisionError:
> >   import traceback
> >   err = traceback.format_exc()
> > Then the formatted exception will be available in 'err'.  Do you want
> > the exception-handling to be part of the function you are entering
> > into 'env'?
> My goal is to execute a function received from a third-part, so I cannot
> modify as you made in your first piece of code.
> I want a "clean" exception with the real line code/tb so I can show a
> "real" error message. This means that the try/execpt has to include the
> passed function and catch every possible exception.
> Do you have any ideas on how can I figure this out?
> Thanks,
> Michele

Exceptions are only caught when raised in a 'try' statement.  If you
don't raise the exception in a try statement, it won't be caught.

The function you posted will raise an exception.  If you are making
the call yourself, that is, if only the definition is foreign, then
simply catch exceptions when so.

Otherwise, my only idea so far is to use the 'ast' module to inject an
exception handler into the third-party function.  That is quite
advanced and may be error-prone, though I think it would look
something like this:

for every 'def' statement in STR:
   def_statement.body= try_statement + def_statement.body

I expect it would be more reliable than hand-parsing the text and
concatenating a string exception statement.

Any interest in this, or do you make the call yourself?

More information about the Python-list mailing list