I\'ve heard the advice that you should avoid try catch blocks if possible since they\'re expensive.
My question is specifically about the .NET platform: Why are try
I think people really overestimate the performance cost of throwing exceptions. Yes, there's a performance hit, but it's relatively tiny.
I ran the following test, throwing and catching a million exceptions. It took about 20 seconds on my Intel Core 2 Duo, 2.8 GHz. That's about 50K exceptions a second. If you're throwing even a small fraction of that, you've got some architecture problems.
Here's my code:
using System;
using System.Diagnostics;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
try
{
throw new Exception();
}
catch {}
}
Console.WriteLine(sw.ElapsedMilliseconds);
Console.Read();
}
}
}