如何更昂贵的是一个例外而不是返回值? [英] How much more expensive is an Exception than a return value?
本文介绍了如何更昂贵的是一个例外而不是返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能改变这个code,有一个返回值,异常:
公共富酒吧(酒吧B)
{
如果(b.Success)
{
返回b;
}
其他
{
扔n.Exception;
}
}
到这一点,这将引发对成功和失败不同的异常
公共富酒吧(酒吧B)
{
扔b.Success?新BarException(二):新FooException();
}
尝试
{
酒吧(二)
}
赶上(BarException BEX)
{
返回ex.Bar;
}
赶上(FooException FEX)
{
Console.WriteLine(fex.Message);
}
解决方案
抛出异常,绝对是比返回的值更昂贵。但在原料成本方面很难说有多少更昂贵的除外。
在上一个返回值与异常决定你应该总是考虑以下规则。
仅用于特殊情况下的例外
它们不应该被使用于一般的控制流程。
Is it possible to change this code, with a return value and an exception:
public Foo Bar(Bar b)
{
if(b.Success)
{
return b;
}
else
{
throw n.Exception;
}
}
to this, which throws separate exceptions for success and failure
public Foo Bar(Bar b)
{
throw b.Success ? new BarException(b) : new FooException();
}
try
{
Bar(b)
}
catch(BarException bex)
{
return ex.Bar;
}
catch(FooException fex)
{
Console.WriteLine(fex.Message);
}
解决方案
Throwing an exception is definitely more expensive than returning a value. But in terms of raw cost it's hard to say how much more expensive an exception is.
When deciding on a return value vs. an exception you should always consider the following rule.
Only use exceptions for exceptional circumstances
They shouldn't ever be used for general control flow.
这篇关于如何更昂贵的是一个例外而不是返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文