Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Propagating c++ exception to cython - python exception

I have a problem with Cython 0.17.1

My function throws a std::runtime_error if a file doesn't exist, I'd like to propagate this exception in some manner to my Cython code.

void loadFile(const string &filename)
{
    // some code, if filename doesn't exists 
    throw std::runtime_error( std::string("File doesn't exists" ) );
}

and from Cython after the right wrapping of the function:

try:
    loadFile(myfilename)
except RuntimeError:
    print "Can't load file"

but this exception is always ignored, how can I catch c++ exceptions from Python?

like image 878
linello Avatar asked Nov 01 '12 20:11

linello


Video Answer


2 Answers

Are you declaring the exception handling with the extern? You should read about C++ exception handling: http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#exceptions

Basically, you need to do something like the following:

cdef extern from "some_file.h":
    cdef int foo() except +
like image 127
kitti Avatar answered Sep 20 '22 12:09

kitti


Declare your function as except +, see http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#exceptions

like image 42
robertwb Avatar answered Sep 20 '22 12:09

robertwb