]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/python/doc/reference/exception_translator.qbk
bump version to 12.2.2-pve1
[ceph.git] / ceph / src / boost / libs / python / doc / reference / exception_translator.qbk
1 [section boost/python/exception_translator.hpp]
2 [section Introduction]
3 As described [link high_level_components.boost_python_errors_hpp.introduction here], it is important to make sure that exceptions thrown by C++ code do not pass into the Python interpreter core. By default, Boost.Python translates all C++ exceptions thrown by wrapped functions and module init functions into Python, but the default translators are extremely limited: most C++ exceptions will appear in Python as a [@http://www.python.org/doc/current/lib/module-exceptions.html RuntimeError] exception whose representation is 'Unidentifiable C++ Exception'. To produce better error messages, users can register additional exception translators as described below.
4 [endsect]
5 [section Function `register_exception_translator`]
6 ``
7 template<class ExceptionType, class Translate>
8 void register_exception_translator(Translate translate);
9 ``
10 [variablelist
11 [[Requires][Translate is CopyConstructible, and the following code must be well-formed:
12 ``void f(ExceptionType x) { translate(x); }``.
13 The expression `translate(x)` must either throw a C++ exception, or a subsequent call to `PyErr_Occurred()` must return 1. ]]
14 [[Effects][Adds a copy of translate to the sequence of exception translators tried when Boost.Python catches an exception that is about to pass into Python's core interpreter. The new translator will get "first shot" at translating all exceptions matching the catch clause shown above. Any subsequently-registered translators will be allowed to translate the exception earlier. A translator which cannot translate a given C++ exception can re-throw it, and it will be handled by a translator which was registered earlier (or by the default translator).]]
15 ]
16 [endsect]
17 [section Example]
18 ``
19 #include <boost/python/module.hpp>
20 #include <boost/python/def.hpp>
21 #include <boost/python/exception_translator.hpp>
22 #include <exception>
23
24 struct my_exception : std::exception
25 {
26 char const* what() throw() { return "One of my exceptions"; }
27 };
28
29 void translate(my_exception const& e)
30 {
31 // Use the Python 'C' API to set up an exception object
32 PyErr_SetString(PyExc_RuntimeError, e.what());
33 }
34
35 void something_which_throws()
36 {
37 ...
38 throw my_exception();
39 ...
40 }
41
42 BOOST_PYTHON_MODULE(exception_translator_ext)
43 {
44 using namespace boost::python;
45 register_exception_translator<my_exception>(&translate);
46
47 def("something_which_throws", something_which_throws);
48 }
49 ``
50 [endsect]
51 [endsect]