Error Handling for COM Servers
When you implement a COM object, it’s often necessary to return error information to the caller. Although Python has a powerful exception mechanism, the caller of your objects is likely to be Visual Basic or Delphi, so standard Python exceptions don’t really work.
To support this, the
win32com.server.exception
module exposes the
COMException
Python object in order to raise an
exception to COM. This object allows you to specify many details
about the error, including the error message, the name of the
application generating the error, the name of a help file in which
the user can find additional information, etc. See the
win32com.server.exception module for more details.
The PythonCOM framework makes the assumption that all Python
exceptions other than COMException indicate a
bug in your
code. Thus, your object shouldn’t allow normal Python
exceptions to be raised when calling your methods, but should take
steps to handle these Python exceptions and translate them to an
appropriate COMException.
As an example, let’s assume you want to publish a method called
sqrt() that returns the square root of its
argument. If you use the following code:
def sqrt(self, val):
return math.sqrt(val)you have a potential problem; in fact, a few of them. If you pass anything other than a positive number to your function, the code fails, and a Python exception is raised. This is considered a bug in your COM object. To improve this function, use the following code:
def sqrt(self, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access