C# catch(FileNotFoundException) and CA1031

Cod*_*gry 6 c# code-analysis

So this code triggers CA1031.

try
{
    // logic
}
catch (FileNotFoundException) // exception type
{
    // handle error
}
Run Code Online (Sandbox Code Playgroud)

While this one does not:

try
{
    // logic
}
catch (FileNotFoundException ex) // exception var
{
    // handle error
}
Run Code Online (Sandbox Code Playgroud)

Because the exception type is meaningful, I don't need the ex in the first example. But it's not a a general exception type. It's not IOException or Exception. So why does it still trigger the CA1031?

So is there a difference between catch(FileNotFoundException) and catch(FileNotFoundException ex) outside the fact that I don't capture exception info?

Çöđ*_*xěŕ 5

所以这段代码触发了CA1031

try
{
    // logic
}
catch (FileNotFoundException) // exception type
{
    // handle error
}
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为“在 catch 语句中捕获了诸如System.Exception或 之类的一般异常System.SystemException,或者使用了诸如 catch() 之类的一般 catch 子句”。要修复它,分配它并处理错误,或者重新抛出一般异常以便进一步处理。

经过进一步调查,这似乎曾经是一个错误,您可以在此处查看更多信息;这是一个Roslyn问题FxCop

修复: 只需更新最新的 FxCop 分析器包,它就可以了。

纽格:

 Install-Package Microsoft.CodeAnalysis.FxCopAnalyzers -Version 2.9.7
Run Code Online (Sandbox Code Playgroud)

参考文献: CA1031