Cython -Python异常传播C 例外

Propagating c++ exception to cython - python exception

本文关键字:例外 传播 异常 -Python Cython      更新时间:2023-10-16

我有Cython 0.17.1

的问题

我的功能会抛出 std::runtime_error如果文件不存在,我想以某种方式传播此例外。

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

和右包装后的Cython:

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

但是总是忽略了这个例外,我如何从python捕获C 例外?

您是否正在声明与外部的异常处理?您应该阅读有关C 异常处理的信息:http://docs.cython.org/src/userguide/wrapping_cplusplus.html#exceptions

基本上,您需要执行以下操作:

cdef extern from "some_file.h":
    cdef int foo() except +

将您的函数声明为except +,请参见http://docs.cython.org/src/src/userguide/wrapping_cplusplus.html#exceptions