Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching COMException specific Error Code

Tags:

c#

com

I'm hoping someone can help me. I've got a specific Exception from COM that I need to catch and then attempt to do something else, all others should be ignored. My error message with the Exception is:

System.Runtime.InteropServices.COMException (0x800A03EC): Microsoft Office Excel cannot access the file 'C:\test.xls'. There are several possible reasons:

So my initial attempt was

try {  // something } catch (COMException ce) {    if (ce.ErrorCode == 0x800A03EC)    {       // try something else     } } 

However then I read a compiler warning:

Warning 22 Comparison to integral constant is useless; the constant is outside the range of type 'int' .....ExcelReader.cs 629 21

Now I know the 0x800A03EC is the HResult and I've just looked on MSDN and read:

HRESULT is a 32-bit value, divided into three different fields: a severity code, a facility code, and an error code. The severity code indicates whether the return value represents information, warning, or error. The facility code identifies the area of the system responsible for the error.

So my ultimate question, is how do I ensure that I trap that specific exception? Or how do I get the error code from the HResult?

Thanks in advance.

like image 838
Ian Avatar asked Sep 15 '09 09:09

Ian


2 Answers

The ErrorCode should be an unsigned integer; you can perform the comparison as follows:

try {     // something } catch (COMException ce) {     if ((uint)ce.ErrorCode == 0x800A03EC) {         // try something else      } } 
like image 95
Paolo Tedesco Avatar answered Sep 24 '22 04:09

Paolo Tedesco


An HRESULT value has 32 bits divided into three fields: a severity code, a facility code, and an error code. The severity code indicates whether the return value represents information, warning, or error. The facility code identifies the area of the system responsible for the error. The error code is a unique number that is assigned to represent the exception. Each exception is mapped to a distinct HRESULT. Excerpt from: http://en.wikipedia.org/wiki/HRESULT

From what I gather, the first half of the HRESULT bits may change depending on the system/process that causes the exception. The second half contains the error type.

Code should look like:

try {     // something } catch (COMException ce) {     if ((uint)ce.ErrorCode & 0x0000FFFF == 0x800A03EC) {         // try something else      } } 

NOTE: please keep in mind I'm not a .NET guy, so be weary of syntax errors in the above code.

like image 24
Scoobie Avatar answered Sep 21 '22 04:09

Scoobie