try except inside exec

Michele Petrazzo michele.petrazzo at
Fri May 29 11:55:01 EDT 2009

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?


More information about the Python-list mailing list