exceptions.rst revision 14299
111986Sandreas.sandberg@arm.comExceptions 211986Sandreas.sandberg@arm.com########## 311986Sandreas.sandberg@arm.com 411986Sandreas.sandberg@arm.comBuilt-in exception translation 511986Sandreas.sandberg@arm.com============================== 611986Sandreas.sandberg@arm.com 711986Sandreas.sandberg@arm.comWhen C++ code invoked from Python throws an ``std::exception``, it is 811986Sandreas.sandberg@arm.comautomatically converted into a Python ``Exception``. pybind11 defines multiple 911986Sandreas.sandberg@arm.comspecial exception classes that will map to different types of Python 1011986Sandreas.sandberg@arm.comexceptions: 1111986Sandreas.sandberg@arm.com 1211986Sandreas.sandberg@arm.com.. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}| 1311986Sandreas.sandberg@arm.com 1414299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 1514299Sbbruce@ucdavis.edu| C++ exception type | Python exception type | 1614299Sbbruce@ucdavis.edu+======================================+======================================+ 1714299Sbbruce@ucdavis.edu| :class:`std::exception` | ``RuntimeError`` | 1814299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 1914299Sbbruce@ucdavis.edu| :class:`std::bad_alloc` | ``MemoryError`` | 2014299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 2114299Sbbruce@ucdavis.edu| :class:`std::domain_error` | ``ValueError`` | 2214299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 2314299Sbbruce@ucdavis.edu| :class:`std::invalid_argument` | ``ValueError`` | 2414299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 2514299Sbbruce@ucdavis.edu| :class:`std::length_error` | ``ValueError`` | 2614299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 2714299Sbbruce@ucdavis.edu| :class:`std::out_of_range` | ``IndexError`` | 2814299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 2914299Sbbruce@ucdavis.edu| :class:`std::range_error` | ``ValueError`` | 3014299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 3114299Sbbruce@ucdavis.edu| :class:`pybind11::stop_iteration` | ``StopIteration`` (used to implement | 3214299Sbbruce@ucdavis.edu| | custom iterators) | 3314299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 3414299Sbbruce@ucdavis.edu| :class:`pybind11::index_error` | ``IndexError`` (used to indicate out | 3514299Sbbruce@ucdavis.edu| | of bounds access in ``__getitem__``, | 3614299Sbbruce@ucdavis.edu| | ``__setitem__``, etc.) | 3714299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 3814299Sbbruce@ucdavis.edu| :class:`pybind11::value_error` | ``ValueError`` (used to indicate | 3914299Sbbruce@ucdavis.edu| | wrong value passed in | 4014299Sbbruce@ucdavis.edu| | ``container.remove(...)``) | 4114299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 4214299Sbbruce@ucdavis.edu| :class:`pybind11::key_error` | ``KeyError`` (used to indicate out | 4314299Sbbruce@ucdavis.edu| | of bounds access in ``__getitem__``, | 4414299Sbbruce@ucdavis.edu| | ``__setitem__`` in dict-like | 4514299Sbbruce@ucdavis.edu| | objects, etc.) | 4614299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 4714299Sbbruce@ucdavis.edu| :class:`pybind11::error_already_set` | Indicates that the Python exception | 4814299Sbbruce@ucdavis.edu| | flag has already been set via Python | 4914299Sbbruce@ucdavis.edu| | API calls from C++ code; this C++ | 5014299Sbbruce@ucdavis.edu| | exception is used to propagate such | 5114299Sbbruce@ucdavis.edu| | a Python exception back to Python. | 5214299Sbbruce@ucdavis.edu+--------------------------------------+--------------------------------------+ 5311986Sandreas.sandberg@arm.com 5411986Sandreas.sandberg@arm.comWhen a Python function invoked from C++ throws an exception, it is converted 5511986Sandreas.sandberg@arm.cominto a C++ exception of type :class:`error_already_set` whose string payload 5611986Sandreas.sandberg@arm.comcontains a textual summary. 5711986Sandreas.sandberg@arm.com 5811986Sandreas.sandberg@arm.comThere is also a special exception :class:`cast_error` that is thrown by 5911986Sandreas.sandberg@arm.com:func:`handle::call` when the input arguments cannot be converted to Python 6011986Sandreas.sandberg@arm.comobjects. 6111986Sandreas.sandberg@arm.com 6211986Sandreas.sandberg@arm.comRegistering custom translators 6311986Sandreas.sandberg@arm.com============================== 6411986Sandreas.sandberg@arm.com 6511986Sandreas.sandberg@arm.comIf the default exception conversion policy described above is insufficient, 6611986Sandreas.sandberg@arm.compybind11 also provides support for registering custom exception translators. 6711986Sandreas.sandberg@arm.comTo register a simple exception conversion that translates a C++ exception into 6811986Sandreas.sandberg@arm.coma new Python exception using the C++ exception's ``what()`` method, a helper 6911986Sandreas.sandberg@arm.comfunction is available: 7011986Sandreas.sandberg@arm.com 7111986Sandreas.sandberg@arm.com.. code-block:: cpp 7211986Sandreas.sandberg@arm.com 7311986Sandreas.sandberg@arm.com py::register_exception<CppExp>(module, "PyExp"); 7411986Sandreas.sandberg@arm.com 7511986Sandreas.sandberg@arm.comThis call creates a Python exception class with the name ``PyExp`` in the given 7611986Sandreas.sandberg@arm.commodule and automatically converts any encountered exceptions of type ``CppExp`` 7711986Sandreas.sandberg@arm.cominto Python exceptions of type ``PyExp``. 7811986Sandreas.sandberg@arm.com 7911986Sandreas.sandberg@arm.comWhen more advanced exception translation is needed, the function 8011986Sandreas.sandberg@arm.com``py::register_exception_translator(translator)`` can be used to register 8111986Sandreas.sandberg@arm.comfunctions that can translate arbitrary exception types (and which may include 8211986Sandreas.sandberg@arm.comadditional logic to do so). The function takes a stateless callable (e.g. a 8311986Sandreas.sandberg@arm.comfunction pointer or a lambda function without captured variables) with the call 8411986Sandreas.sandberg@arm.comsignature ``void(std::exception_ptr)``. 8511986Sandreas.sandberg@arm.com 8611986Sandreas.sandberg@arm.comWhen a C++ exception is thrown, the registered exception translators are tried 8711986Sandreas.sandberg@arm.comin reverse order of registration (i.e. the last registered translator gets the 8811986Sandreas.sandberg@arm.comfirst shot at handling the exception). 8911986Sandreas.sandberg@arm.com 9011986Sandreas.sandberg@arm.comInside the translator, ``std::rethrow_exception`` should be used within 9111986Sandreas.sandberg@arm.coma try block to re-throw the exception. One or more catch clauses to catch 9211986Sandreas.sandberg@arm.comthe appropriate exceptions should then be used with each clause using 9311986Sandreas.sandberg@arm.com``PyErr_SetString`` to set a Python exception or ``ex(string)`` to set 9411986Sandreas.sandberg@arm.comthe python exception to a custom exception type (see below). 9511986Sandreas.sandberg@arm.com 9611986Sandreas.sandberg@arm.comTo declare a custom Python exception type, declare a ``py::exception`` variable 9711986Sandreas.sandberg@arm.comand use this in the associated exception translator (note: it is often useful 9811986Sandreas.sandberg@arm.comto make this a static declaration when using it inside a lambda expression 9911986Sandreas.sandberg@arm.comwithout requiring capturing). 10011986Sandreas.sandberg@arm.com 10111986Sandreas.sandberg@arm.com 10211986Sandreas.sandberg@arm.comThe following example demonstrates this for a hypothetical exception classes 10311986Sandreas.sandberg@arm.com``MyCustomException`` and ``OtherException``: the first is translated to a 10411986Sandreas.sandberg@arm.comcustom python exception ``MyCustomError``, while the second is translated to a 10511986Sandreas.sandberg@arm.comstandard python RuntimeError: 10611986Sandreas.sandberg@arm.com 10711986Sandreas.sandberg@arm.com.. code-block:: cpp 10811986Sandreas.sandberg@arm.com 10911986Sandreas.sandberg@arm.com static py::exception<MyCustomException> exc(m, "MyCustomError"); 11011986Sandreas.sandberg@arm.com py::register_exception_translator([](std::exception_ptr p) { 11111986Sandreas.sandberg@arm.com try { 11211986Sandreas.sandberg@arm.com if (p) std::rethrow_exception(p); 11311986Sandreas.sandberg@arm.com } catch (const MyCustomException &e) { 11411986Sandreas.sandberg@arm.com exc(e.what()); 11511986Sandreas.sandberg@arm.com } catch (const OtherException &e) { 11611986Sandreas.sandberg@arm.com PyErr_SetString(PyExc_RuntimeError, e.what()); 11711986Sandreas.sandberg@arm.com } 11811986Sandreas.sandberg@arm.com }); 11911986Sandreas.sandberg@arm.com 12011986Sandreas.sandberg@arm.comMultiple exceptions can be handled by a single translator, as shown in the 12111986Sandreas.sandberg@arm.comexample above. If the exception is not caught by the current translator, the 12211986Sandreas.sandberg@arm.compreviously registered one gets a chance. 12311986Sandreas.sandberg@arm.com 12411986Sandreas.sandberg@arm.comIf none of the registered exception translators is able to handle the 12511986Sandreas.sandberg@arm.comexception, it is handled by the default converter as described in the previous 12611986Sandreas.sandberg@arm.comsection. 12711986Sandreas.sandberg@arm.com 12811986Sandreas.sandberg@arm.com.. seealso:: 12911986Sandreas.sandberg@arm.com 13011986Sandreas.sandberg@arm.com The file :file:`tests/test_exceptions.cpp` contains examples 13111986Sandreas.sandberg@arm.com of various custom exception translators and custom exception types. 13211986Sandreas.sandberg@arm.com 13311986Sandreas.sandberg@arm.com.. note:: 13411986Sandreas.sandberg@arm.com 13511986Sandreas.sandberg@arm.com You must call either ``PyErr_SetString`` or a custom exception's call 13611986Sandreas.sandberg@arm.com operator (``exc(string)``) for every exception caught in a custom exception 13711986Sandreas.sandberg@arm.com translator. Failure to do so will cause Python to crash with ``SystemError: 13811986Sandreas.sandberg@arm.com error return without exception set``. 13911986Sandreas.sandberg@arm.com 14011986Sandreas.sandberg@arm.com Exceptions that you do not plan to handle should simply not be caught, or 14114299Sbbruce@ucdavis.edu may be explicitly (re-)thrown to delegate it to the other, 14211986Sandreas.sandberg@arm.com previously-declared existing exception translators. 143