try exec

Ype Kingma ykingma at
Thu Jan 16 22:28:05 CET 2003

Afanasiy wrote:

> Some code I "exec" throws a TypeError exception. I want it to throw this
> exception but want to be able to catch this along with the others which
> are in fact being caught by the try/except block.
> The specific TypeError in this case is caused by a module-defined
> function being called with the incorrect number of arguments. Again,
> I want to catch this exception. The problem is, this exception, unlike
> the others, is not being caught/handled by my try/except block.

How do you know it is thrown?
> Can someone tell me why this is and perhaps how I can catch it?

The try/except below should catch a TypeError.
However, I'd prefer to control the namespace in which exec
is executing. You are not doing this now, so exec executes
in the namespace it happens to be in, ie. your module's
namespace. This might cause unexpected results, but
I would not expect from the code you posted.

Adding namespace gives:
> i=0

namespace = {}

> for line, expecting in lines:
>   i+=1

print repr(namespace)

>   print '[%d] %s' % (i, line)

print '[%d %d] %s' % (i, expecting, line)

>   try:
>     exec line
    exec line in namespace
>     if expecting==0:
>       printerror('this should have thrown an exception')
>   except:
>     print '\t '+repr(sys.exc_value.args)
>     if expecting==1:
>       printerror('this should not be an exception')
> ---
> The structure of "lines" is :
> lines = [
>   ('foo = MyModule.Something()',1),
>   ('foo.Function("hmm")',0),
>   ...etc..
> ]

Good luck,

More information about the Python-list mailing list