[Cython] Exception instantiation

Robert Bradshaw robertwb at gmail.com
Wed Mar 21 19:56:37 CET 2012


On Wed, Mar 21, 2012 at 1:03 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Hi,
>
> I was made aware of a difference between the ways Cython and CPython raise
> exceptions. In CPython, the exception is always instantiated immediately,
> even if you raise a plain type, i.e.
>
>    raise TypeError
>
> will actually raise a TypeError() instance. In Cython, the exception is
> only stored, not instantiated. The difference can show when the
> instantiation fails for some reason or has other side effects. Depending on
> *when* and *if* the exception is actually instantiated, these effects may
> show at unexpected times during execution, or may be not occur at all in
> some corner cases (e.g. when the exception is shadowed by another one in
> Py2 or caught by an except block in Cython that contains only C code).
>
> I think this should change. We may consider leaving it as it is for known
> exception types that are created without arguments, but otherwise, and
> especially for user provided exceptions, we should take the safer route of
> always instantiating them, like CPython does. That implies a certain
> performance hit in some rather rare cases (of which an explicitly raised
> StopIteration is the most visible one, if not exempted), but under normal
> conditions where an exception is regularly caught at some point, the
> overhead is the same and it would have less surprising corner cases.

+1. One could consider making an exception for the no-argument builtin
(side-effect-free) ones, but this would just be an optimization, and
we're typically already in an expensive, exceptional state at this
point.

- Robert


More information about the cython-devel mailing list