“使用例外来控制流”的例子 [英] Example of "using exceptions to control flow"

查看:117
本文介绍了“使用例外来控制流”的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What would a piece of code which "uses exceptions to control flow" look like? I've tried to find a direct C# example, but cannot. Why is it bad?

谢谢

推荐答案



下面的代码捕获到一个可以很容易地避免的异常。这使得代码更难以遵循,并且通常也会导致性能成本。

Bad

The below code catches an exception that could easily be avoided altogether. This makes the code more difficult to follow and typically incurs a performance cost as well.

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.");
}



更好的



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

Better

This code checks for a condition that would throw an exception, and corrects the situation before the error occurs. This way there is no exception at all. The code is more readable, and the performance is very likely to be better.

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);

这篇关于“使用例外来控制流”的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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