24 #ifndef LSST_PEX_EXCEPTIONS_PYTHON_EXCEPTION_H
25 #define LSST_PEX_EXCEPTIONS_PYTHON_EXCEPTION_H
29 #include <pybind11/pybind11.h>
35 namespace exceptions {
51 template <
typename T,
typename E = lsst::pex::exceptions::Exception>
61 py::class_<T, E>
cls(mod,
name.c_str());
67 py::reinterpret_steal<py::object>(PyImport_ImportModule(
"lsst.pex.exceptions.wrappers"));
68 if (!exceptions.ptr()) {
69 PyErr_SetString(PyExc_SystemError,
"import failed");
70 throw py::error_already_set();
73 auto declare = py::reinterpret_steal<py::object>(PyObject_GetAttrString(exceptions.ptr(),
"declare"));
75 PyErr_SetString(PyExc_SystemError,
"could not get declare function from Python");
76 throw py::error_already_set();
79 auto baseCls = py::reinterpret_steal<py::object>(PyObject_GetAttrString(exceptions.ptr(),
base.c_str()));
81 PyErr_SetString(PyExc_SystemError,
"could not get base class");
82 throw py::error_already_set();
85 auto exceptionName = py::reinterpret_steal<py::object>(PYBIND11_FROM_STRING(
name.c_str()));
86 if (!exceptionName.ptr()) {
87 PyErr_SetString(PyExc_SystemError,
"could not create name string");
88 throw py::error_already_set();
91 auto result = py::reinterpret_steal<py::object>(PyObject_CallFunctionObjArgs(
92 declare.ptr(), mod.ptr(), exceptionName.ptr(), baseCls.ptr(),
cls.ptr(), NULL));
94 PyErr_SetString(PyExc_SystemError,
"could not declare exception");
95 throw py::error_already_set();