SWIG and Python: define custom exception on Python side

I was able to use %exception with C# and Java to throw custom exception classes which I wrote by hand in the target language.

I use %exception with Python too but with Python’s built-in PyExc_Exception type and this works:

try:
  do();
except Exception as ex:
  print(ex)

Is there a way to achieve the following?

try:
  do();
except CustomException as ex:
  print(ex)

If possible without wrapping C++’s CustomException class, but just defining it on the Python side, although any solution would do

class CustomException(Exception):
     def __init__(self, value):
         self.value = value
     def __str__(self):
         return repr(self.value)


Source: python

Leave a Reply