I am writing a Python program that interfaces with Quickbooks. When connecting to Quickbooks, depending on the problem, I might get one of two common exceptions:
As soon as I posted I found the way to catch the exception in a non-generic manner in a question that appeared in the Related sidebar. Here is the way to capture these exceptions:
from pywintypes import com_error
except com_error as e:
Note that the differing reasons for the exception cannot be handled individually, so the return code must be examined inside the except
clause by comparing the value of e.exceptinfo[5]
:
except com_error as e:
if e.excepinfo[5] == -2147220464:
print('Please change the Quickbooks mode to Multi-user Mode.')
elif e.excepinfo[5] == -2147220472:
print('Please start Quickbooks.')
else:
raise e
I had considered marking this question as a dupe, but considering that none of the other related questions handle the situation of distinguishing between the different exceptions thrown under this single type, I leave this one as it addresses this issue and answers it.
Now pywintypes.error
is BaseException
.
There is no need to from pywintypes import com_error
.
If you want to catch this exception.
You can just catch BaseException
except BaseException as e: # to catch pywintypes.error
print(e.args)
the exception's format likes this:
(0, 'SetForegroundWindow', 'No error message is available')
So If you want to examine the return code,use e.args[0]
instead of e.exceptinfo[5]