gpt4 book ai didi

c# - C# 中的一般异常处理

转载 作者:太空狗 更新时间:2023-10-29 19:50:12 25 4
gpt4 key购买 nike

我正在通过 FxCop 运行一些代码,目前正在考虑清除所有非破坏性违规。

代码本身有几个 try/catch block 的实例,它们只捕获一般异常;

try
{
// Some code in here that could throw an exception
}
catch(Exception ex)
{
// Exception Thrown ... sort it out!
}

现在我们都知道这是不好的做法,但我认为我知道如何正确地做到这一点 - 但 FxCop 有其他想法!

假设 try block 中的代码可以抛出一个 IO 异常 - 并且只是一个 IO 异常。这样做应该没有错:

try
{
// Code in here that can only throw an IOException
}
catch (System.IO.IOException ioExp)
{
// Handle the IO exception or throw it
}
catch (System.Exception ex)
{
// Catch otherwise unhandled exception
}

但 FxCop 不同意我的看法……它仍然将此标记为违规,因为我正在捕获 System.Exception

这是真的不好的做法还是我应该/可以安全地忽略这种违规行为?

最佳答案

我同意 FxCop 和此处的大多数其他答案:不要捕获 System.Exception ever,除非它在您的应用程序中处于最高级别以进行记录意外(因此是致命的)异常,然后轰炸应用程序。 Also check out this question that's basically about the same thing.

其他一些有效的异常(exception)可能是:

  • 为了重新抛出更具描述性的异常而捕获异常。
  • 在需要比 ExpectedExceptionAttribute 更复杂的东西的单元测试代码中。
  • 在 Facade 库中,代码的存在只是为了保护调用者免受调用某些外部(网络)服务的复杂性的影响,而无论外部系统出现多么严重的故障,它自己都不会真正失败。

关于c# - C# 中的一般异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1629794/

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