Jan 17, 2009

What is the cost of catching an exception

We all known that following an exception without using it is quite silly. How does it really hurt performance. It turns out that difference is very small.

DateTime entry = DateTime.Now;

for (int i = 0; i  < 100000; i++)
{
    try
    {
        throw new Exception("something wrong");
    }
    //catch 
    catch (Exception ex)
    {
    }

}


DateTime exit = DateTime.Now;

TimeSpan ts = exit - entry;
Console.WriteLine(ts.TotalMilliseconds);

//catch 2593.7002
//no catch 2531.2014