问题描述
我希望有人可以帮助我.我有一个来自 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无法访问文件C: est.xls".有几个可能的原因:
System.Runtime.InteropServices.COMException (0x800A03EC): Microsoft Office Excel cannot access the file 'C: est.xls'. There are several possible reasons:
所以我最初的尝试是
try
{
// something
}
catch (COMException ce)
{
if (ce.ErrorCode == 0x800A03EC)
{
// try something else
}
}
然后我读到了编译器警告:
However then I read a compiler warning:
警告 22 与积分比较常数是无用的;常数是超出类型范围'int' .....ExcelReader.cs 629 21
Warning 22 Comparison to integral constant is useless; the constant is outside the range of type 'int' .....ExcelReader.cs 629 21
现在我知道 0x800A03EC 是HResult,我刚刚在 MSDN 上看过并阅读:
Now I know the 0x800A03EC is the HResult and I've just looked on MSDN and read:
HRESULT 是一个 32 位的值,分为三个不同的领域:严重性代码、设施代码和错误代码.严重性代码表示是否返回值表示信息、警告或错误.设施代码标识负责的系统区域错误.
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.
所以我的最终问题是,我如何确保捕获该特定异常?或者如何从 HResult 中获取错误代码?
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?
提前致谢.
推荐答案
ErrorCode 应该是一个无符号整数;您可以按如下方式进行比较:
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
}
}
这篇关于捕获 COMException 特定的错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!