Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 215
abatishchev Avatar asked Aug 15 '09 16:08

abatishchev


People also ask

Is it expensive to throw exceptions?

Since throwing and handling exceptions is expensive, we shouldn't use it for normal program flows. Instead, as its name implies, exceptions should only be used for exceptional cases. The complete source code can be found over on GitHub.

Which is better a return code or an exception?

An application that uses exceptions is more robust than an application that uses return codes. An application that uses exceptions can also give the cleanest code, since return codes don't have to be checked after every call.

Why are exceptions so expensive?

So we clearly see there is an extra cost for exception handling that increases the deeper the stack trace goes. This is because when an exception is thrown the runtime needs to search up the stack until it hits a method than can handle it. The further it has to look up the stack, the more work it has to do.

Why is using exceptions a better idea than returning an error value?

Return codes are more brittle The error is ignored when "returned", and will possibly explode later (i.e. a NULL pointer). The same problem won't happen with exception. The error won't be ignored.


1 Answers

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.

like image 183
JaredPar Avatar answered Sep 22 '22 05:09

JaredPar