一段“使用异常控制流”的代码会是什么样子的?我试图找到一个直接的C#示例,但是找不到。为什么它不好呢?
谢谢
发布于 2010-07-16 04:21:29
坏的
下面的代码捕获了一个可以很容易地完全避免的异常。这使得代码更难理解,而且通常也会产生性能成本。
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.");
}更好
此代码检查可能引发异常的条件,并在错误发生之前更正该情况。这样就不会有任何例外。代码更具可读性,性能很可能会更好。
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);发布于 2010-07-16 04:22:05
根据定义,异常是发生在软件正常流程之外的事件。我脑海中有一个简单的例子,就是使用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.在本例中,您没有使用File.Exists()方法,该方法实现了相同的结果,但没有异常的开销。
除了错误的使用,还有与异常、填充属性、创建堆栈跟踪等相关的开销。
发布于 2010-07-16 04:23:53
它大体上等同于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正如您所看到的,它正在运行一些(虚构的)测试;如果测试失败,就会抛出一个异常,并且worked将被设置为false。
当然,直接更新bool worked要容易得多!
希望这能有所帮助!
https://stackoverflow.com/questions/3259660
复制相似问题