Catching a pywintypes.api_error excpeption?

Mark Hammond mhammond at skippinet.com.au
Fri Aug 2 15:25:10 CEST 2002


Peter Hansen wrote:
> Derek Basch wrote:
> 
>>Hi,
>>Can someone tell me how to catch this exception with a
>>try, except clause:
>>
>>    SetCommState(self.handle, dcb)
>>pywintypes.api_error: (87, 'SetCommState', 'The
>>parameter is incorrect.')
>>
>>every exception I have previously worked with has been
>>a class such as IOError. How do i catch this one?
> 
> 
> As with "except IOError", just use the name of the class:
> 
> try:
>     SetCommState(self.handle, dcb)
> except pywintypes.api_error:
>     print 'spam spam spam spam'

It *should* be pywintypes.api_error, but for historical reasons this is 
not correct :(  I have finally fixed it so the exception printed is 
'pywintypes.error', which is actually an exception you can catch.

In the win32 extensions, every module exposes an 'error' object - and 
all are the exact same error object.  Thus, as these functions come from 
win32file, you typically catch win32file.error, but pywintypes.error, 
and basically win32*.error, will all work.

ie:

 >>> pywintypes.error is win32file.error
True

> (Although this sounds more like an exception coming from
> a bug, not a runtime condition that you would want to catch
> like an IOError.)

No, this is just the standard exception raised by the win32 exceptions 
whenever the underlying win32 API function fails.  The error code is in 
the exception.

Mark.




More information about the Python-list mailing list