Skip to content

Commit c6d6d8a

Browse files
committed
Error handling
1 parent 0a15fa1 commit c6d6d8a

1 file changed

Lines changed: 47 additions & 3 deletions

File tree

include/openPMD/binding/python/Numpy.hpp

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,53 @@ inline Datatype dtype_from_numpy(pybind11::object const &dt)
106106
}
107107
else
108108
{
109-
auto numpy = pybind11::module_::import("numpy");
110-
auto create_dtype = numpy.attr("dtype");
111-
return dtype_from_numpy(py::cast<pybind11::dtype>(create_dtype(dt)));
109+
pybind11::module_ numpy;
110+
try
111+
{
112+
numpy = pybind11::module_::import("numpy");
113+
}
114+
catch (std::exception const &e)
115+
{
116+
throw std::runtime_error(
117+
std::string(
118+
"dtype_from_numpy: Cannot convert from object type to "
119+
"datatype without numpy, failed importing: ") +
120+
e.what());
121+
}
122+
pybind11::object create_dtype;
123+
try
124+
{
125+
create_dtype = numpy.attr("dtype");
126+
}
127+
catch (std::exception const &e)
128+
{
129+
throw std::runtime_error(
130+
std::string(
131+
"dtype_from_numpy: Failed to access numpy.dtype: ") +
132+
e.what());
133+
}
134+
pybind11::object dtype_obj;
135+
try
136+
{
137+
dtype_obj = create_dtype(dt);
138+
}
139+
catch (std::exception const &e)
140+
{
141+
throw std::runtime_error(
142+
std::string("dtype_from_numpy: Failed to create dtype from: ") +
143+
pybind11::str(dt).cast<std::string>() +
144+
std::string(", error: ") + e.what());
145+
}
146+
try
147+
{
148+
return dtype_from_numpy(py::cast<pybind11::dtype>(dtype_obj));
149+
}
150+
catch (std::exception const &e)
151+
{
152+
throw std::runtime_error(
153+
std::string("dtype_from_numpy: Failed to cast to dtype: ") +
154+
e.what());
155+
}
112156
}
113157
}
114158

0 commit comments

Comments
 (0)