try except inside exec

Aaron Brady castironpi at
Fri May 29 16:38:46 CEST 2009

On May 29, 8:21 am, Michele Petrazzo
<michele.petrazzo at> wrote:
> Hi all,
> I want to execute a python code inside a string and so I use the exec
> statement. The strange thing is that the try/except couple don't catch
> the exception and so it return to the main code.
> Is there a solution to convert or make this code work?
> Thanks,
> Michele
> My code:
> STR = """
> err = 0
> try:
>    def a_funct():
>      1/0
> except:
>    import traceback
>    err = traceback.format_exc()
> """
> env = {}
> exec STR in env
> env["a_funct"]()
> print env["err"]
> My error:
>    File "tmp/", line 14, in <module>
>      env["a_funct"]()
>    File "<string>", line 5, in a_funct
> ZeroDivisionError: integer division or modulo by zero

The code you posted defines a function, and if the definition of it
raises an exception, it will enter your except clause.  By the way,
you generally should avoid 'bare' except clauses, and specify the type
of error you want to catch, in this case, 'ZeroDivisionError', as you
see (just good practice stuff).

It's not clear from your attempt what your exact goal was.  You
probably mean:

STR = """
class Globals:
   err = 0
def a_funct():
   except ZeroDivisionError:
      import traceback
      Globals.err = traceback.format_exc()

Note that the formatted exception will be available in 'env
["Globals"].err'.  But you could also mean:

exec STR in env
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'?

More information about the Python-list mailing list