gpt4 book ai didi

c# - 捕获 COMException 特定的错误代码

转载 作者:IT王子 更新时间:2023-10-29 04:21:09 24 4
gpt4 key购买 nike

我希望有人能帮助我。我有一个来自 COM 的特定异常,我需要捕获它然后尝试做其他事情,所有其他的都应该被忽略。我的异常错误消息是:

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

所以我最初的尝试是

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

然后我读到一个编译器警告:

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

现在我知道 0x800A03EC 是HResult 和我刚刚查看了 MSDN并阅读:

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 获取错误代码?

提前致谢。

最佳答案

ErrorCode 应该是一个无符号整数;您可以按如下方式进行比较:

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

关于c# - 捕获 COMException 特定的错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1426147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com