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()实现相同结果但没有异常开销的方法.
除了不良用法之外,还存在与异常相关的开销,填充属性,创建堆栈跟踪等.
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)
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当然,直接更新更容易!
希望有所帮助!
这是一个常见的:
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)
| 归档时间: |
|
| 查看次数: |
3864 次 |
| 最近记录: |