From 6c1a433c4c6933ec1be1643df67197b00e225d97 Mon Sep 17 00:00:00 2001 From: Pavel Rojtberg Date: Tue, 2 Feb 2021 02:49:19 +0100 Subject: [PATCH] python: also catch general c++ exceptions they might be thrown from third-party code (notably Ogre in the ovis module). While Linux is kind enough to print them, they cause instant termination on Windows. Arguably, they do not origin from OpenCV itself, but still this helps understanding what went wrong when calling an OpenCV function. --- modules/core/include/opencv2/core/bindings_utils.hpp | 8 ++++++++ modules/python/src2/cv2.cpp | 5 +++++ modules/python/test/test_misc.py | 6 ++++++ 3 files changed, 19 insertions(+) diff --git a/modules/core/include/opencv2/core/bindings_utils.hpp b/modules/core/include/opencv2/core/bindings_utils.hpp index bbcc3a88d0..179d60323f 100644 --- a/modules/core/include/opencv2/core/bindings_utils.hpp +++ b/modules/core/include/opencv2/core/bindings_utils.hpp @@ -8,6 +8,8 @@ #include #include +#include + namespace cv { namespace utils { //! @addtogroup core_utils //! @{ @@ -113,6 +115,12 @@ String dumpRange(const Range& argument) } } +CV_WRAP static inline +void testRaiseGeneralException() +{ + throw std::runtime_error("exception text"); +} + CV_WRAP static inline AsyncArray testAsyncArray(InputArray argument) { diff --git a/modules/python/src2/cv2.cpp b/modules/python/src2/cv2.cpp index 8272513e64..8bb15cd43f 100644 --- a/modules/python/src2/cv2.cpp +++ b/modules/python/src2/cv2.cpp @@ -206,6 +206,11 @@ catch (const cv::Exception &e) \ { \ pyRaiseCVException(e); \ return 0; \ +} \ +catch (const std::exception &e) \ +{ \ + PyErr_SetString(opencv_error, e.what()); \ + return 0; \ } using namespace cv; diff --git a/modules/python/test/test_misc.py b/modules/python/test/test_misc.py index 5e23045e05..121e86a64c 100644 --- a/modules/python/test/test_misc.py +++ b/modules/python/test/test_misc.py @@ -47,6 +47,12 @@ class Bindings(NewOpenCVTests): boost.getMaxDepth() # from ml::DTrees boost.isClassifier() # from ml::StatModel + def test_raiseGeneralException(self): + with self.assertRaises((cv.error,), + msg='C++ exception is not propagated to Python in the right way') as cm: + cv.utils.testRaiseGeneralException() + self.assertEqual(str(cm.exception), 'exception text') + def test_redirectError(self): try: cv.imshow("", None) # This causes an assert