Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling. How long does catch take? [duplicate]

Possible Duplicate:
How slow are .NET exceptions?

Is there an overhead for throwing an exception and catching it right away? Is there a difference between this

void DoSomething(object basic)
{
    try
    {
       if (basic == null)
         throw new NullReferenceException("Any message");
       else
       {
         //...
       }
    }
    catch (Exception error)
    {
       _logger.WriteLog(error);
    }
}

and this (here we don't throw exception):

void DoSomething(object basic)
{
    try
    {
        if (basic == null)
        {
            _logger.WriteLog(new NullReferenceException("Any message");
            return;
        }
        else
        {
         ...
        }
    }
    catch (Exception error)
    {
        _logger.WriteLog(error);
    }
}

Will the second fragment be faster, or not?

Also I want to know why one solution is faster than another.

like image 968
Daniil Grankin Avatar asked Sep 10 '12 13:09

Daniil Grankin


1 Answers

Exceptions are slower than all other program flow but not to the extent they should be avoided for performance reasons. However, they are not meant to be used for program flow. In your situation, you have a very valid alternative that is better than using exceptions. When you can predict a situation and handle it appropriately without exceptions, always do that. Also, don't use exceptions in normal program flow as a convenience.

Use exceptions when you have an unanticipated exceptional situation you can't handle directly.

like image 103
Samuel Neff Avatar answered Sep 20 '22 14:09

Samuel Neff