exceptions.rst revision 11986
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
1411986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
1511986Sandreas.sandberg@arm.com|  C++ exception type                  |  Python exception type       |
1611986Sandreas.sandberg@arm.com+======================================+==============================+
1711986Sandreas.sandberg@arm.com| :class:`std::exception`              | ``RuntimeError``             |
1811986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
1911986Sandreas.sandberg@arm.com| :class:`std::bad_alloc`              | ``MemoryError``              |
2011986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
2111986Sandreas.sandberg@arm.com| :class:`std::domain_error`           | ``ValueError``               |
2211986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
2311986Sandreas.sandberg@arm.com| :class:`std::invalid_argument`       | ``ValueError``               |
2411986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
2511986Sandreas.sandberg@arm.com| :class:`std::length_error`           | ``ValueError``               |
2611986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
2711986Sandreas.sandberg@arm.com| :class:`std::out_of_range`           | ``ValueError``               |
2811986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
2911986Sandreas.sandberg@arm.com| :class:`std::range_error`            | ``ValueError``               |
3011986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
3111986Sandreas.sandberg@arm.com| :class:`pybind11::stop_iteration`    | ``StopIteration`` (used to   |
3211986Sandreas.sandberg@arm.com|                                      | implement custom iterators)  |
3311986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
3411986Sandreas.sandberg@arm.com| :class:`pybind11::index_error`       | ``IndexError`` (used to      |
3511986Sandreas.sandberg@arm.com|                                      | indicate out of bounds       |
3611986Sandreas.sandberg@arm.com|                                      | accesses in ``__getitem__``, |
3711986Sandreas.sandberg@arm.com|                                      | ``__setitem__``, etc.)       |
3811986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
3911986Sandreas.sandberg@arm.com| :class:`pybind11::value_error`       | ``ValueError`` (used to      |
4011986Sandreas.sandberg@arm.com|                                      | indicate wrong value passed  |
4111986Sandreas.sandberg@arm.com|                                      | in ``container.remove(...)`` |
4211986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
4311986Sandreas.sandberg@arm.com| :class:`pybind11::key_error`         | ``KeyError`` (used to        |
4411986Sandreas.sandberg@arm.com|                                      | indicate out of bounds       |
4511986Sandreas.sandberg@arm.com|                                      | accesses in ``__getitem__``, |
4611986Sandreas.sandberg@arm.com|                                      | ``__setitem__`` in dict-like |
4711986Sandreas.sandberg@arm.com|                                      | objects, etc.)               |
4811986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
4911986Sandreas.sandberg@arm.com| :class:`pybind11::error_already_set` | Indicates that the Python    |
5011986Sandreas.sandberg@arm.com|                                      | exception flag has already   |
5111986Sandreas.sandberg@arm.com|                                      | been initialized             |
5211986Sandreas.sandberg@arm.com+--------------------------------------+------------------------------+
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
14111986Sandreas.sandberg@arm.com    may be explicity (re-)thrown to delegate it to the other,
14211986Sandreas.sandberg@arm.com    previously-declared existing exception translators.
143