如果条件与异常处理程序 [英] if-condition vs exception handler

查看:45
本文介绍了如果条件与异常处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题:


您更喜欢什么,异常处理还是if条件?

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

进行采访。我的回答是,仅在异常情况下(例如文件写入中的磁盘权限错误)才首选使用异常处理程序。面试官似乎在期待其他答案。正确的答案是什么?

for an interview. My answer was that exception handlers are preferred only for exceptional circumstances like a disk permission error on file write. The interviewer seemed to be expecting some other answer. What is the correct answer?

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

Any particular example where exception handling is commonly used when an if-condition would have been more appropriate?

推荐答案

由于此问题被标记为 C#,因此我们可以参考《 .NET Framework设计指南》作为回答此类问题的良好起点。这是在MSDN上异常抛出

As this question is tagged "C#", we can refer to the .NET Framework Design Guidelines as a good starting point for answering these types of questions. This is the guidance given on MSDN under "Exception Throwing":


如果可能的话,不要对正常的控制流程使用异常。除了
用于系统故障和具有潜在竞争条件的操作外,
框架设计人员应设计API,以便用户可以编写不会引发异常的代码
。例如,您可以提供一种在调用成员之前检查
前提条件的方法,以便用户可以编写不会引发异常的
代码。

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.

这里是做法的示例,其中处理异常但几乎总是可以避免:

Here is an example of a bad practice where an exception is handled but can nearly always be avoided:

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

    return value;
}

这似乎是人为的,但是我经常从新的程序员那里看到这样的代码。假设围绕 array 的读写进行适当的同步,则可以确定性地避免这种异常。鉴于此,编写该代码的更好方法如下:

This seems contrived but I see code like this quite often from newer programmers. Assuming proper synchronization around reads and writes to array, this exception can be 100% deterministically avoided. Given that, a better way to write that code would be the following:

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中的示例

There are other cases where you cannot reasonably avoid exceptions and just need to handle them. This is most commonly encountered when you have to deal with external resources such as files or network connections which you could potentially lose access to or contact with at any time. Example from 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()检查,后面是适当的异常处理逻辑。

Even in the above example, it's good to check that the operation you are going to do at least has a chance of succeeding. So there is still an if () check, followed by the appropriate exception handling logic.

这篇关于如果条件与异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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