Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom Python exception type in C extension?

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.

How do I throw custom Python exceptions from C code?

like image 646
Basilevs Avatar asked Jun 20 '11 12:06

Basilevs


People also ask

How can you create your own exceptions in Python?

Creating Custom Exceptions In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.

What is type extension in Python?

Overview. The typing_extensions module serves two related purposes: Enable use of new type system features on older Python versions. For example, typing. TypeGuard is new in Python 3.10, but typing_extensions allows users on Python 3.6 through 3.9 to use it too.

What is custom exception explain it using example?

In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the 'throw' keyword. For example, MyException in the below code extends the Exception class.


1 Answers

The easiest way to create a new exception type in C code is to call PyErr_NewException.

like image 62
Sven Marnach Avatar answered Oct 17 '22 01:10

Sven Marnach