14

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?

linello
  • 8,451
  • 18
  • 63
  • 109
  • Did you use [`except +`](http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#exceptions) in your `cdef`? – user4815162342 Nov 01 '12 at 21:45
  • yes, probably I should post some more code... – linello Nov 02 '12 at 14:21
  • Are you absolutely sure the exception is thrown on the C++ side? You could also try replacing `except RuntimeError` with `except Exception, e` and print `e` to see if maybe some other Python exception is raised. – user4815162342 Nov 02 '12 at 15:03

2 Answers2

7

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 +
kitti
  • 14,663
  • 31
  • 49
1

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

robertwb
  • 4,891
  • 18
  • 21