如何在C扩展中创建自定义Python异常类型? [英] How to create a custom Python exception type in C extension?
问题描述
我正在用C编写Python模块.我需要报告无法由内置Python异常描述的错误.因此,我希望抛出自己类型的异常.问题在于,Python策略是从BaseException类派生所有异常.我知道如何创建派生类型对象(分配给tp_base成员),但是我不知道如何获取对BaseException类型对象的引用.PyExc_BaseException是对PyObject的引用,表示一个类,而不是类型对象.
I'm writing a Python module in C. I need to report errors that can't be described by built-in Python exceptions. I therefore wish to throw exceptions of my own type. The problem is, that Python policy is to derive all exceptions from BaseException class. I know how to create a derived type object (assigning to tp_base memeber), but I don't know how to obtain a reference to BaseException type object. PyExc_BaseException is a reference to PyObject, representing a class, not a type object.
如何从C代码中引发自定义Python异常?
How do I throw custom Python exceptions from C code?
推荐答案
The easiest way to create a new exception type in C code is to call PyErr_NewException
.
这篇关于如何在C扩展中创建自定义Python异常类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!