"使用异常来控制流"的示例

Gur*_*epS 7 c# exception-handling exception

一段"使用异常来控制流"的代码是什么样的?我试图找到一个直接的C#示例,但不能.为什么不好?

谢谢

Eri*_*son 14

根据定义,异常是在软件正常流程之外发生的事件.我头顶的一个简单示例是使用a FileNotFoundException来查看文件是否存在.

try
{
    File.Open(@"c:\some nonexistent file.not here");
}
catch(FileNotFoundException)
{
    // do whatever logic is needed to create the file.
    ...
}
// proceed with the rest of your program.
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您没有使用File.Exists()实现相同结果但没有异常开销的方法.

除了不良用法之外,还存在与异常相关的开销,填充属性,创建堆栈跟踪等.

  • 哎哟,不是一个好例子.File.Exists()不是*在多任务操作系统上的可靠替代品. (8认同)

Dan*_*Tao 10

下面的代码捕获了一个可以轻松完全避免的异常.这使代码更难以遵循,并且通常也会产生性能成本.

int input1 = GetInput1();
int input2 = GetInput2();

try
{
    int result = input1 / input2;
    Output("{0} / {1} = {2}", input1, input2, result);
}
catch (OverflowException)
{
    Output("There was an overflow exception. Make sure input2 is not zero.");
}
Run Code Online (Sandbox Code Playgroud)

更好

此代码检查引发异常的条件,并在错误发生之前更正该情况.这样就没有例外.代码更具可读性,性能很可能更好.

int input1 = GetInput1();
int input2 = GetInput2();

while (input2 == 0)
{
    Output("input2 must not be zero. Enter a new value.");
    input2 = GetInput2();
}

int result = input1 / input2;
Output("{0} / {1} = {2}", input1, input2, result);
Run Code Online (Sandbox Code Playgroud)

  • 因此,归结为不使用异常来执行逻辑来修复异常并在事先进行验证?因此,异常应该用于真正特殊的事情而不是真的可以预见. (4认同)

Kie*_*one 10

它大致等同于goto,除了Exception这个词更糟糕,并且开销更大.你告诉代码跳转到catch块:

bool worked;
try
{
    foreach (Item someItem in SomeItems)
    {
        if (someItem.SomeTestFailed()) throw new TestFailedException();
    }
    worked = true;
}
catch(TestFailedException testFailedEx)
{
    worked = false;
}
if (worked) // ... logic continues
Run Code Online (Sandbox Code Playgroud)

如你所见,它正在运行一些(补偿)测试; 如果它们失败,则抛出异常,并将worked设置为false.

bool worked当然,直接更新更容易!

希望有所帮助!

  • +1虽然其他一些例子也在控制流量,但我认为这是一个被警告的噩梦场景. (2认同)

Tob*_*oby 5

这是一个常见的:

public bool TryParseEnum<T>(string value, out T result)
{
    result = default(T);

    try
    {
        result = (T)Enum.Parse(typeof(T), value, true);
        return true;
    }
    catch
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)