Handling exception thrown by Boost.Python c-extension in Python code

MarkE mark.english at rbccm.com
Tue Mar 27 14:01:01 EDT 2007


I'm just getting started on Boost Python and may have missed this
obvious looking problem somewhere.

Given a c-extension "testext" written using Boost Python containing a
base class "Base", a derived class "Derived", and a function
"doSomething" which expects a "Derived" parameter, if I pass it a
"Base" parameter an exception is thrown. This is a
Boost.Python.ArgumentError. My question is how do I catch this error ?

I tried the following bit of investigation:
#Start code
import testext
b = testext.Base()
try:
   testext.doSomething(b)
except Exception, e:
    pass
help(e.__class__)
#End code

which produces
#Start output
Help on class ArgumentError:

class ArgumentError(exceptions.TypeError)
 |  Method resolution order:
 |      ArgumentError
 |      exceptions.TypeError
 |      exceptions.StandardError
 |      exceptions.Exception
 |
 |  Methods inherited from exceptions.Exception:
 |
 |  __getitem__(...)
 |
 |  __init__(...)
 |
 |  __str__(...)
#End output

"print e" produces "<Boost.Python.ArgumentError instance>"

So I could handle this by writing an except clause for TypeError.

Boost.Python doesn't exist as a module i.e. it's not in sys.modules,
and I don't know how to import it - should there be a Boost.Python
module somewhere on my PythonPath that I've forgotten to setup ?
Is there a standard way of catching these errors by their actual
type ?
Is there an easy way to export the exception classes from my c-
extension (testext) so that I can use that ? Thus "except
testext.ArgumentError" would catch the "Boost.Python.ArgumentError" ?

Thanks for any help,
Mark




More information about the Python-list mailing list