Polymorphic exception handling: How to catch subclass exception? Polymorphic exception handling: How to catch subclass exception? python python

Polymorphic exception handling: How to catch subclass exception?


My python skills are rusty and I haven't tested this, so this may need further improvements, but try adding the exception translation method to handle the base class exception type:

static PyObject *clusterExecutionAsClusterExceptionType = NULL;static void translateClusterExecutionAsClusterException(ClusterException const &exception) {  ClusterExecutionException* upcasted = dynamic_cast<ClusterExecutionException*>(&exception);  if (upcasted)  {    assert(clusterExecutionAsClusterExceptionType != NULL);    boost::python::object pythonExceptionInstance(*upcasted);  PyErr_SetObject(clusterExecutionAsClusterExceptionType, pythonExceptionInstance.ptr());  }}register_exception_translator<ClusterException>(&translateClusterExecutionAsClusterException);


I don't know about your C++ code. But there is small problem with your python code. Catch ClusterExecutionException before ClusterException. You should always put child exception handler before base exception.

In test_exception if ClusterExecutionException raised it will be catch by ClusterException before it could reach ClusterExecutionException.

code should be as below code

def test_exception(exCase):    try:        cluster.boomTest(exCase)    except ClusterExecutionException as ex:        print 'Success! ClusterExecutionException gracefully handled:' \            '\n message="%s"' \            '\n errorType="%s"' \            '\n clusterResponse="%s"' % (ex.message, ex.errorType, ex.clusterResponse)    except ClusterException as ex:        print 'Success! ClusterException gracefully handled:' \            '\n message="%s"' % ex.message    except:        print 'Caught unknown exception: %s "%s"' % (sys.exc_info()[0], sys.exc_info()[1])

now do I have tried in Boost-Python while registering the exception translation of ClusterExecutionException to register it as its base ClusterException , what you have mentioned in question.