C# 将catch(COMException ce)更改为catch(COMException)
我有以下代码:C# 将catch(COMException ce)更改为catch(COMException),c#,com,exception-handling,C#,Com,Exception Handling,我有以下代码: try { retval = axNTLXRemote.IsUnitPresent(_servers[0].IPAddress, 1, _servers[0].RemotePort, _servers[0].CommFailDelay * 1000); } catch (COMException ce) { throw ce; } 这给了我以下的警告
try
{
retval = axNTLXRemote.IsUnitPresent(_servers[0].IPAddress, 1, _servers[0].RemotePort, _servers[0].CommFailDelay * 1000);
}
catch (COMException ce)
{
throw ce;
}
这给了我以下的警告,我想摆脱它:
CA2200:Microsoft。用法:“Connect()”重新引发捕获的异常,并将其显式指定为参数。改用不带参数的“throw”,以保留最初引发异常的堆栈位置。
我已经阅读了以下内容,并且我理解;将重置堆栈跟踪并使其显示为异常是从该函数引发的
我想简单地将其更改为“throw”,而不是“throw-ce”,这样可以消除警告
catch (COMException ce)
{
throw;
}
及
这两种情况并没有区别,但只有当异常变量应用于堆栈/消息等时才有区别 因此: 及 语句将生成类似的MSIL,但ComException对象的局部变量除外:
.locals init ([0] class [mscorlib]System.Exception ex)
我相信有人会给出一个uber技术性的答案,但根据我的经验,前两个问题的答案是没有区别的,正如你所说,如果你打算使用它将堆栈跟踪写入日志或向用户显示消息或类似内容,你只会包含
ce
抛出
将异常发送到链的上游。这可能是调用方法,或者,如果您的方法有多个嵌套的try/catch块,它将向当前try/catch块嵌套的下一个try/catch块发送异常
如果您想进一步阅读有关该主题的内容,请参阅以下几篇好的参考资料:
catch(COMException ce)
,您将异常分配给变量,从而允许您在catch
块中访问它。除此之外,它在各个方面都是相同的catch
子句中为其指定一个变量名catch
块void Method1()
{
try
{
Method2();
}
catch // this will catch *any* exception
{
}
}
void Method2()
{
try
{
Method3();
}
catch (COMException ex) // this will catch only COMExceptions and exceptions that derive from COMException
{
}
}
void Method3()
{
// if this code were here, it would be caught in Method2
throw new COMException();
// if this code were here, it would be caught in Method1
throw new ApplicationException();
}
好建议。更好的建议是去掉try/catch,它不会做任何有用的事情。我继承了一个充斥着try/catch的项目,因此我正在尝试整理警告等。在这个阶段,我无法去掉所有警告。因此,如果我进一步查看链(或寻找另一个嵌套的catch)没有看到其他使用ce变量的东西,那么我知道我可以安全地删除它????
catch(ComException ex);
.locals init ([0] class [mscorlib]System.Exception ex)
void Method1()
{
try
{
Method2();
}
catch // this will catch *any* exception
{
}
}
void Method2()
{
try
{
Method3();
}
catch (COMException ex) // this will catch only COMExceptions and exceptions that derive from COMException
{
}
}
void Method3()
{
// if this code were here, it would be caught in Method2
throw new COMException();
// if this code were here, it would be caught in Method1
throw new ApplicationException();
}