C extension module doesn't throw exception after setting error indicator through PyErr_SetString()

Tim Golden mail at timgolden.me.uk
Thu Aug 2 06:45:47 EDT 2012


On 02/08/2012 10:50, rahul wrote:
> When I use same code base for Python 3.x, then behavior is different. In this when I return false then also it throws exception but only when any other statement get executed after this 
> 
> like below code:
>  ...
>  ...
>    b = None
>    try:
>      a = testModule.check(None)
>    except:
>      b = sys.exc_info()
> then code execution doesn't come to except block.
> But when I add one statement after calling check function then code execution goes into except block. 
> 
>  ...
>  ...
>  b = None
>  try:
>    a = testModule.check(None)
>    print( a )
>  except:
>    b = sys.exc_info()


Sounds like you're entering into undefined behaviour. If you set an
exception and don't return NULL, you're leaving Python's internals in an
inconsistent state. I don't know the internal code paths, but presumably
in one version it just ignored the exception state while in the other it
noticed it but in a different point in the code at which point it raised
the exception. Or something.

Long-and-short: return NULL from an extension module function once
you've raised (or are cascading) an exception condition. Anything else
is undefined unless you know *exactly* what you're doing.


TJG



More information about the Python-list mailing list