C#catch(FileNotFoundException)和CA1031 [英] C# catch(FileNotFoundException) and CA1031

查看:95
本文介绍了C#catch(FileNotFoundException)和CA1031的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此此代码触发 CA1031

try
{
    // logic
}
catch (FileNotFoundException) // exception type
{
    // handle error
}

而这不是:

try
{
    // logic
}
catch (FileNotFoundException ex) // exception var
{
    // handle error
}

因为异常类型很有意义,所以我不需要 ex 在第一个示例中。但这不是一般的例外类型。它不是 IOException Exception 。那么为什么它仍会触发 CA1031

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?

所以 catch之间有区别吗(FileNotFoundException) catch(FileNotFoundException ex)在我未捕获异常信息的事实之外?

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

推荐答案


因此该代码触发 CA1031



try
{
    // logic
}
catch (FileNotFoundException) // exception type
{
    // handle error
}

这是因为诸如 System.Exception System.SystemException 之类的异常被捕获在catch语句或常规的catch子句中catch()被使用。要对其进行修复,请对其进行分配并处理该错误,或​​者重新抛出一般异常以使其得到进一步处理。

This occurs because a "general exception such as System.Exception or System.SystemException is caught in a catch statement, or a general catch clause such as catch() is used". To fix it, assign it and handle the error and or rethrow the general exception for it to be handled further up.

在进一步调查中,似乎使用了 是一个错误,您可以在此处;这是 FxCop Roslyn 问题。

Upon further investigation, it seems this used to be an bug, you can see more here; it was a Roslyn issue for FxCop.

要修复:
只需更新最新的FxCop分析仪软件包,它应该就会成功。

To Fix: Just update the latest FxCop analyzers package and it should go way.

NuGet:

 Install-Package Microsoft.CodeAnalysis.FxCopAnalyzers -Version 2.9.7

参考:
CA1031

这篇关于C#catch(FileNotFoundException)和CA1031的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆