c# - if 条件与异常处理程序

标签 c#

我的问题是:

"What do you prefer, exception handling or if-condition?"

接受采访。我的回答是,异常处理程序仅适用于特殊情况,例如文件写入时的磁盘权限错误。面试官似乎在期待其他答案。正确答案是什么?

编辑:当 if 条件更合适时通常使用异常处理的任何特定示例?

最佳答案

由于这个问题被标记为“C#”,我们可以引用 .NET Framework 设计指南作为回答此类问题的良好起点。这是 MSDN 上 "Exception Throwing" 下给出的指南:

Do not use exceptions for normal flow of control, if possible. Except for system failures and operations with potential race conditions, framework designers should design APIs so that users can write code that does not throw exceptions. For example, you can provide a way to check preconditions before calling a member so that users can write code that does not throw exceptions.

这里是一个实践的例子,其中异常被处理但几乎总是可以避免的:

public int? GetItem(int index)
{
    int? value = null;
    try
    {
        value = this.array[index];
    }
    catch (IndexOutOfRangeException)
    {
    }

    return value;
}

这似乎是做作的,但我经常从新程序员那里看到这样的代码。假设对 array 的读取和写入正确同步,则可以 100% 确定性地避免此异常。鉴于此,编写该代码的更好方法如下:

public int? GetItem(int index)
{
    int? value = null;

    // Ensure the index is within range in the first place!
    if (index >= 0 && index < this.array.Length)
    {
        value = this.array[index];
    }

    return value;
}

还有其他情况,您无法合理地避免异常而只需要处理它们。当您必须处理外部资源(如文件或网络连接)时,您最常遇到这种情况,您可能随时无法访问或联系这些资源。来自 WCF 的示例:

public void Close()
{
    // Attempt to avoid exception by doing initial state check
    if (this.channel.State == CommunicationState.Opened)
    {
        try
        {
            // Now we must do a (potentially) remote call;
            // this could always throw.
            this.channel.Close();
        }
        catch (CommunicationException)
        {
        }
        catch (TimeoutException)
        {
        }
    }

    // If Close failed, we might need to do final cleanup here.
    if (this.channel.State == CommunicationState.Faulted)
    {
        // local cleanup -- never throws (aside from catastrophic situations)
        this.channel.Abort();
    }
}

即使在上面的示例中,也最好检查您将要执行的操作是否至少有成功的机会。所以还是有一个if ()检查,然后是相应的异常处理逻辑。

关于c# - if 条件与异常处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8687113/

相关文章:

c# - 每当修改一个字段时修改另一个字段

c# - 复制流

c# - 序列不包含匹配元素 - 使用 LINQ 返回匹配自定义属性的 SiteMapNode

c# - 计算结果 LINQ

c# - 使用泛型委托(delegate)时如何理解逆变?

c# - 当我尝试保存图像时收到错误 "A generic error occurred in GDI+."

c# - 从大字符串中提取数据

c# - MonoTouch - 无法加载 bundle : 'NSBundle' 中的 NIB

c# - 如果元素中存在属性,则将 XAttribute 添加到 XElement

c# - 如何将字符串 1 的确切位置获取到字符串 2 C#