如何更昂贵的是一个例外而不是返回值?的是、昂贵、返回值、而不是

2023-09-02 20:47:30 作者:怎忆初相逢

是否有可能改变这个code,有一个返回值,异常:

 公共富酒吧(酒吧B)
{
   如果(b.Success)
   {
      返回b;
   }
   其他
   {
      扔n.Exception;
   }
}
 

到这一点,这将引发对成功和失败不同的异常

 公共富酒吧(酒吧B)
{
   扔b.Success?新BarException(二):新FooException();
}

尝试
{
   酒吧(二)
}
赶上(BarException BEX)
{
   返回ex.Bar;
}
赶上(FooException FEX)
{
   Console.WriteLine(fex.Message);
}
 

解决方案

抛出异常,绝对是比返回的值更昂贵。但在原料成本方面很难说有多少更昂贵的除外。

我很内向 用英语怎么说 真的不是I m shy

在上一个返回值与异常决定你应该总是考虑以下规则。

  

仅用于特殊情况下的例外

它们不应该被使用于一般的控制流程。

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.