2012-07-12 133 views

回答

2

Jim Bosch在C++-sig list上提出的一個可行解決方案是使用組合而不是從包裝的C++異常繼承。代碼必須像here那樣創建Python異常,然後將包裝的C++異常添加爲Python異常的實例變量。

void translator(const MyCPPException &x) { 
    bp::object exc(x); // wrap the C++ exception 

    bp::object exc_t(bp::handle<>(bp::borrowed(exceptionType))); 
    exc_t.attr("cause") = exc; // add the wrapped exception to the Python exception 

    PyErr_SetString(exceptionType, x.what()); 
} 

包裹的C++異常然後可以從Python的訪問這樣的:

try: 
    ... 
except MyModule.MyCPPExceptionType as e: 
    cause = e.cause # wrapped exception can be accessed here 

但異常還將由

try: 
    ... 
except Exception: 
    ... 
+1

注意,'exc_t.attr(「原因被捕獲「)= exc;'將C++異常實例作爲屬性添加到Python異常*類*中。因此,如果您在Python中捕獲了一個異常實例e1並保留對它的引用,那麼第二次引發這種C++異常將會改變e1的cause屬性來引用新的C++異常實例。 – Holger 2015-04-24 09:24:38