How much more expensive is an Exception than a return value?

.net, c#, exception, return-value

Solution

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.

Problem

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); } ```

Original source