The Dangers Of Exception Based Logic Part 1 - Parsing Integers

Exception based logic is one of those things that actually makes me cringe when I see it.  Often times it is really easy to avoid like in the case below.  Believe it or not, exceptions in .NET aren't cheap and shouldn't be taken for granted.

 

Exception Based Logic:     14-19ms

Try Function Based Logic: 0ms

 

 static void Main(string[] args)
{
    using (new QuickTimer("Exception Based Logic"))
    {
         for (int i = 0; i < 10; i++)
         {
             try
             {
                 int j = Int32.Parse("a");
             } catch (Exception ex)
             {
                 Console.WriteLine("Error");
             }
         }
    }

    using (new QuickTimer("Try Function Based Logic"))
    {
         for (int i = 0; i < 10; i++)
         {
              int j = 0;
              if (!Int32.TryParse("a",out j))
              {
                  Console.WriteLine("Error");
              }
         }
      }
}