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.
They shouldn’t ever be used for general control flow.