Raising exception in def __init__() causes python crash

15 views
Skip to first unread message

Toni Barth

unread,
Apr 25, 2018, 3:08:38 AM4/25/18
to cython...@googlegroups.com
Hi,

OK, so i'm currently using Cython again to optimize code for speed and
performance, reading and processing files.
I created an extension type like the following:

from .exceptions import PGMEOF, PGMError

cimport cython
from libc.stdio cimport FILE, fopen, fgetc, fseek, fclose, feof, SEEK_SET

cdef class PGMReader:
cdef FILE* __file
cdef readonly int width
cdef readonly height
cdef readonly int maximum_gray

def __init__(PGMReader self, char *filename):
self.__file = fopen(filename, "r")
if self.__file == NULL:
raise PGMError("File not found")
self.width = 0
self.height = 0
self.maximum_gray = 0

...

When the path to the file is correct, everything works and I can
continue processing the file, but if not, I get a "Python stopped
working" error.

I'm currently running Cython 0.28.2 under Python 2.7.10 x86 on Windows 8.1.

Any ideas why Cython seems to have problems with raising exceptions
inside of my __init__ method?

Thanks.

Best Regards.

Toni

Jeroen Demeyer

unread,
Apr 25, 2018, 3:59:36 AM4/25/18
to cython...@googlegroups.com
On 2018-04-25 09:08, 'Toni Barth' via cython-users wrote:
> Any ideas why Cython seems to have problems with raising exceptions
> inside of my __init__ method?

Cython doesn't have problems with that. The code that you posted looks
fine, so it's probably crashing somewhere else. Maybe you are still
accessing the partially-initialized object somewhere?

Toni Barth

unread,
Apr 25, 2018, 4:04:03 AM4/25/18
to cython...@googlegroups.com
Hi,

yeah, you're right, i'm to blame here. I just added a __dealloc__ def
earlier to clean up, and thought I removed it earlier, but I guess I
simply didn't save the commented state, and inside the __dealloc__ i'm
closing the file handle no matter if its valid or not. I just fixed
it. Thanks anyway.

Best Regards.

Toni
> --
>
> ---
> You received this message because you are subscribed to the Google Groups
> "cython-users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to cython-users...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>
Reply all
Reply to author
Forward
0 new messages