Skip to content

Commit 6c1a433

Browse files
committed
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.
1 parent 23734af commit 6c1a433

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

modules/core/include/opencv2/core/bindings_utils.hpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
#include <opencv2/core/async.hpp>
99
#include <opencv2/core/detail/async_promise.hpp>
1010

11+
#include <stdexcept>
12+
1113
namespace cv { namespace utils {
1214
//! @addtogroup core_utils
1315
//! @{
@@ -113,6 +115,12 @@ String dumpRange(const Range& argument)
113115
}
114116
}
115117

118+
CV_WRAP static inline
119+
void testRaiseGeneralException()
120+
{
121+
throw std::runtime_error("exception text");
122+
}
123+
116124
CV_WRAP static inline
117125
AsyncArray testAsyncArray(InputArray argument)
118126
{

modules/python/src2/cv2.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,11 @@ catch (const cv::Exception &e) \
206206
{ \
207207
pyRaiseCVException(e); \
208208
return 0; \
209+
} \
210+
catch (const std::exception &e) \
211+
{ \
212+
PyErr_SetString(opencv_error, e.what()); \
213+
return 0; \
209214
}
210215

211216
using namespace cv;

modules/python/test/test_misc.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,12 @@ def test_inheritance(self):
4747
boost.getMaxDepth() # from ml::DTrees
4848
boost.isClassifier() # from ml::StatModel
4949

50+
def test_raiseGeneralException(self):
51+
with self.assertRaises((cv.error,),
52+
msg='C++ exception is not propagated to Python in the right way') as cm:
53+
cv.utils.testRaiseGeneralException()
54+
self.assertEqual(str(cm.exception), 'exception text')
55+
5056
def test_redirectError(self):
5157
try:
5258
cv.imshow("", None) # This causes an assert

0 commit comments

Comments
 (0)