Should I always call PyErr_Clear() when an exception occurs?

Jaime Wyant at
Tue Dec 21 18:41:09 CET 2004

On Tue, 21 Dec 2004 01:17:52 -0500, Tim Peters <tim.peters at> wrote:
> [Jaime Wyant]
> > I've found that the code below will crash if I don't have the
> > PyErr_Clear() function call.  Should I always call PyErr_Clear()?
> That's not the right approach.  Nearly all Python C API calls can
> fail.  They return a special value if they do, primarily NULL for a
> call that returns a pointer, or -1 for a call that returns an int.
> The correct thing to do is to explicitly check every call that *might*
> fail to see whether it *did* fail.  If it did, then you also have to
> explictly decide what to do about it:  either pass the exception on to
> your caller (by returning your function's error value), or suppress
> the exception via PyErr_Clear(), or replace it with another exception.
> You have to do one of those before making another Python C API call.
> Ignoring these issues always leads to bad problems eventually.

What exactly "happens" if I leave the exception hanging out there?  It
looked as if the garbage collector was trying to do something with
them.  Anyway, thanks big time for that paragraph above.  I don't seem
to recall the manual telling me when to call PyErr_Clear(), but I was
RTFM'n late into the night.

And you're right, programming in C stinks.   Especially for the novice
Python-C hacker who keeps having to refer to the manual to determine
if I have a borrowed or new reference!

<Snip wonderful words of wisdom!>


More information about the Python-list mailing list