Dil*_*ave 7 c# exception-handling
我正在通过FxCop运行一些代码,目前正在考虑清除所有非破坏性违规.
代码本身有一些try/catch块实例,它们只捕获一般异常;
try
{
// Some code in here that could throw an exception
}
catch(Exception ex)
{
// Exception Thrown ... sort it out!
}
Run Code Online (Sandbox Code Playgroud)
现在我们都知道这是不好的做法,但我认为我知道如何正确地做到这一点 - 但FxCop还有其他想法!
假设try块中的代码可能抛出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
}
Run Code Online (Sandbox Code Playgroud)
但是FxCop不同意我的观点......它仍然将此标记为违规,因为我正在追赶System.Exception
.
这是非常糟糕的做法还是应该/我能否安全地忽略这种违规行为?
我同意的FxCop和大多数其他的答案在这里:别抓System.Exception
过,除非是在你的应用程序日志意外(因而致命)的异常,然后轰炸应用的最高水平.还看看这个基本上是同一件事的问题.
其他一些有效的例外可能是:
ExpectedExceptionAttribute
.我同意其他答案,catch (Exception ex)
如果你们两个都没问题
还有一种情况出现在我的脑海中它可能有意义:在编写无人值守的代码(例如某些系统服务)时,如果某些(明确定义的)子任务因任何问题而失败,那么保持程序运行是完全合理的.原因.当然,必须注意确保记录问题的原因并且(可能)在一段时间后再次尝试该任务.