propagating an exception from a callback function?

410 views
Skip to first unread message

Jason

unread,
Sep 28, 2011, 3:16:29 PM9/28/11
to cython-users
Hi everyone,

I am almost finished with a CPython API -> Cython port that I've been
working on, but I am stuck on one last detail. Currently, we have some
callback functionality, and while I am able to get it to work without
exception handling, I can't figure out how to do it handling
exceptions.

Below is one of the tests that is failing:

class GoodException(Exception):
pass

def callback_raise(info, n_reads, other):
raise GoodException

def test_raise_in_consume_fasta_build_readmask():
kh = khmer.new_hashtable(4, 4**4)

try:
kh.consume_fasta_build_readmask(reads_filename, 0, 0,
callback_raise)
assert 0
except GoodException:
pass
except:
raise

What should occur is that the callback function (callback_raise)
should raise GoodException when consume_fasta_build_readmask is
called. However, this does not occur and assert 0 is called.

This is where I think the problem is in my .pyx file:

cdef void _report_fn(const_char_ptr info, void* data,
unsigned int n_reads, unsigned long long other)
except +:
global _callback_obj
_callback_obj(info, n_reads, other)

I'm not sure exactly _how_ I am supposed to handle the exception here.
In the current CPython API code, PyErr_Occurred() is checked, and if
that is the case, then another exception is thrown.

Can anyone point me in the right direction here? I am clearly not C++,
Python, and/or Cython-savvy enough to put all the pieces together. :-)

Thanks,
Jason

Robert Bradshaw

unread,
Sep 28, 2011, 3:55:25 PM9/28/11
to cython...@googlegroups.com

The "except +" declaration will cause it to catch C++ exceptions,
which are distinct from Python exceptions. Declare your method as
"except *" and it will check the Python error status after the call.

- Robert

Jason

unread,
Sep 28, 2011, 4:56:09 PM9/28/11
to cython-users
Thanks for the reply. I tried changing except + to except *, and I
saw no changes in the results of the test. Is it possible that I need
to explicitly throw an exception in _report_fn?

Jason

On Sep 28, 3:55 pm, Robert Bradshaw <rober...@math.washington.edu>
wrote:

Robert Bradshaw

unread,
Sep 28, 2011, 5:00:57 PM9/28/11
to cython...@googlegroups.com
Both callback_raise and consume_fasta_build_readmask need to be
declared as "except *" (I think, I don't have the complete source
here.)

Jason

unread,
Sep 28, 2011, 5:07:12 PM9/28/11
to cython-users
It worked! Thanks for all of your help.

Jason

On Sep 28, 5:00 pm, Robert Bradshaw <rober...@math.washington.edu>
wrote:
Reply all
Reply to author
Forward
0 new messages