如何正确地引发异常?
我试过以下几种方法:
#[pymethods]
impl Foo {
#[new]
fn __new__(arg1: u8, ...) -> Self {
if arg1 > LIMIT {
let gil = Python::acquire_gil();
let py = gil.python();
PyErr::new::<exceptions::ValueError, _>("Parameter arg1 has invalid value").restore(py);
}
Foo {...}
}这与如何描述这里完全相同。
当我创建一个参数值无效的Foo实例时,将使用错误文本<class 'Foo'> returned a result with an error set来代替ValueError来引发SystemError。
我在Linux上每晚使用pyo3 0.11.1和Rust 1.47.0。
发布于 2020-07-28 08:01:03
您可以使用返回异常(将在python中引发)的PyResult:
#[pymethods]
impl Foo {
#[new]
fn __new__(arg1: u8, ...) -> PyResult<Self> {
if arg1 > LIMIT {
Err(exceptions::PyValueError::new_err("Parameter arg1 has invalid value"))
} else {
Ok(Foo {...})
}
}https://stackoverflow.com/questions/63128052
复制相似问题