diff --git a/python/runtime/cudaq/analysis/py_dem.cpp b/python/runtime/cudaq/analysis/py_dem.cpp index d29d34220d7..65538da1b11 100644 --- a/python/runtime/cudaq/analysis/py_dem.cpp +++ b/python/runtime/cudaq/analysis/py_dem.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include using namespace cudaq; @@ -27,10 +28,23 @@ static std::string dem_from_kernel_impl(const std::string &kernelName, args = simplifiedValidateInputArguments(args); const cudaq::noise_model *noisePtr = noise ? &(*noise) : nullptr; - return cudaq::detail::runDemFromKernel(kernelName, platform, noisePtr, [&]() { - [[maybe_unused]] auto result = - cudaq::marshal_and_launch_module(kernelName, kernelMod, args); - }); + // Re-throw as a module-local RuntimeError; plugin exceptions otherwise + // escape uncaught on macOS and abort instead of raising in Python. + try { + return cudaq::detail::runDemFromKernel( + kernelName, platform, noisePtr, [&]() { + [[maybe_unused]] auto result = + cudaq::marshal_and_launch_module(kernelName, kernelMod, args); + }); + } catch (nanobind::python_error &) { + throw; // keep real Python exceptions (e.g. from argument marshalling) + } catch (const std::exception &e) { + throw std::runtime_error(e.what()); // dem_from_kernel reports via RuntimeError + } catch (...) { + throw std::runtime_error( + "cudaq::dem_from_kernel failed: the kernel uses an operation the Stim " + "analysis backend cannot simulate (only Clifford gates are supported)."); + } } void cudaq::bindDemFromKernel(nanobind::module_ &mod) {