next up previous contents index
Next: Building Python Extension Modules Up: Python Bindings Previous: How to Call Methods   Contents   Index


Catching and Throwing Exceptions in Python

Python exceptions must be Python classes; they cannot be a C extension type -- the mechanism used to wrap SIDL objects as Python objects. Because of this, Babel defines an exception class for each SIDL type that implements sidl.BaseException. For a type called x.y.z, the Python exception class is named x.y.z._Exception. In Babel 0.10.2 and previous releases, the Python exception class was named x.y.z.Exception, but this name can potentially collide with the class constructor or a static method named Exception. For backwards compatibility, Babel defines x.y.z.Exception if the name Exception is not used in the class.

SIDL exceptions are caught and thrown very much like normal Python exceptions are caught and thrown except you need to use the Python exception class for the SIDL type. The exception value holds the SIDL object as attribute exception. Here is an example of a code catching exceptions from a call to getFib. Note that eobj.exception is an instance of ExceptionTest.NegativeValueException.NegativeValueException, the Python type corresponding to the SIDL type ExceptionTest.NegativeValueException.


  try:
    fib.getFib(-1, 10, 10, 0)
  except ExceptionTest.NegativeValueException._Exception:
    (etype, eobj, etb) = sys.exc_info()
    # eobj is the SIDL exception object
    print eobj.exception.getNote()  # show the exception comment
    print eobj.exception.getTrace() # and traceback

Here is an example of a Python implementation function that throws an exception. The setNote method provides a useful error message, and the add method helps provide a multi-language traceback capability (provided each layer of the call stack calls add).


  def getFib(self, n, max_depth, max_value, depth):
    # sidl EXPECTED INCOMING TYPES
    # ============================
    # int n, max_depth, max_value, depth
    #
    # sidl EXPECTED RETURN VALUE(s)
    # =============================
    # int _return
    # DO-NOT-DELETE splicer.begin(getFib)
    if (n < 0):
      ex = ExceptionTest.NegativeValueException.NegativeValueException()
      ex.setNote("n negative")
      ex.add(__name__, 0, "ExceptionTest.Fib.getFib")
      raise ExceptionTest.NegativeValueException._Exception, ex
    # numerous lines deleted
    # DO-NOT-DELETE splicer.end(getFib)


next up previous contents index
Next: Building Python Extension Modules Up: Python Bindings Previous: How to Call Methods   Contents   Index


babel-0.99.0
users_guide Last Modified 2006-06-27

http://www.llnl.gov/CASC/components
components@llnl.gov