NEURON
convert_cxx_exceptions.hpp
Go to the documentation of this file.
1 #pragma once
2 #include <exception>
3 #include <stdexcept>
4 #include <type_traits>
5 
6 namespace nrn {
7 namespace detail {
8 
9 template <class T, class = void>
11 
12 template <>
14  static PyObject* value() {
15  return nullptr;
16  }
17 };
18 
19 template <class T>
21  T,
22  typename std::enable_if<std::is_integral_v<T> && std::is_signed_v<T>>::type> {
23  static T value() {
24  return -1;
25  }
26 };
27 
28 } // namespace detail
29 
30 template <class F, class... Args>
32  using return_type = std::invoke_result_t<F, Args...>;
33 
36  }
37 };
38 
39 template <class F, class... Args>
40 static typename convert_cxx_exceptions_trait<F, Args...>::return_type convert_cxx_exceptions(
41  F f,
42  Args&&... args) {
43  // Same mapping of C++ exceptions to Python errors that pybind11 uses.
44  try {
45  return f(std::forward<Args>(args)...);
46  } catch (const std::bad_alloc& e) {
47  PyErr_SetString(PyExc_MemoryError, e.what());
48  } catch (const std::domain_error& e) {
49  PyErr_SetString(PyExc_ValueError, e.what());
50  } catch (const std::invalid_argument& e) {
51  PyErr_SetString(PyExc_ValueError, e.what());
52  } catch (const std::length_error& e) {
53  PyErr_SetString(PyExc_ValueError, e.what());
54  } catch (const std::out_of_range& e) {
55  PyErr_SetString(PyExc_IndexError, e.what());
56  } catch (const std::range_error& e) {
57  PyErr_SetString(PyExc_ValueError, e.what());
58  } catch (const std::overflow_error& e) {
59  PyErr_SetString(PyExc_OverflowError, e.what());
60  } catch (std::exception& e) {
61  PyErr_SetString(PyExc_RuntimeError, e.what());
62  } catch (...) {
63  PyErr_SetString(PyExc_Exception, "Unknown C++ exception.");
64  }
65 
67 }
68 } // namespace nrn
Definition: bimap.hpp:13
static convert_cxx_exceptions_trait< F, Args... >::return_type convert_cxx_exceptions(F f, Args &&... args)
short type
Definition: cabvars.h:10
_object PyObject
Definition: nrnpy.h:12
static uint32_t value
Definition: scoprand.cpp:25
std::invoke_result_t< F, Args... > return_type