Never use try catch for input validation

Sourav.Kayal
Posted by in C# category on for Beginner level | Points: 250 | Views : 7537 red flag

Performance impact by using try catch in input validation.

Never use try catch for input validation

If you are an experienced developer then probably you know the impact of exception object in application. As object of Exception class takes lot of resources, it is recommended not to throw exception more often in application. Good exception handling mechanism says, “Throw exception only if needed”.

Now, in normal application development it has seen that developer has used exception mechanism to validate user input.

In below example we will validate user input by exception handling mechanism. Try to understand below example.

        public string Name;
        public string GetSetName {
            set {
                if (value == null)
                    throw new Exception("Name cannot be Null");
                else
                    Name = value;
                }
        }

In this example we have declared Name data member in certain class and declare GetSetName property to initialize value into it.

Within property we are checking whether value is null or not, if it is null then we are throwing exception.  It will work perfectly if we set value to this property within try block. And we can show error message within catch block.

But it is not a good practice to throw exception if there is chance to handle situation without exception handling. To raise one exception it takes lot of memory and server resources. In the example below, we will see the performance difference of throwing exception and not throwing exception.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Collections;
using Client;
namespace Client
{
    class TestException
    {
        public int Roll;
        public int SetRollException {
                            get { return Roll; }
                            set {
                                if (value < 0)
                                {
                                    throw new Exception("Input cannot less than 0 ");
                                }
                                else
                                   Roll = value;
                                }
                          }
 
        public int SetRollDefault {
                             set{
                                     if (value < 0)
                                     {
                                         Console.WriteLine("Input cannot less than 0");
                                     }
                                    else
                                       Roll = value;
                                    }
                                }
           
        }
 
 
    }
    class Program
    {
        static void Main(string[] args)
        {
            TestException t = new TestException();
            Stopwatch sw = new Stopwatch();
           
            try
            {
                sw.Start();
                t.SetRollException = -10;
            }
            catch(Exception ex)
            {
                sw.Stop();
                Console.WriteLine(ex.Message);
                Console.WriteLine("Using Exception handeling:- " + sw.ElapsedTicks + "\n");
            }
 
            sw.Restart();
            t.SetRollDefault = -10;
            sw.Stop();
            Console.WriteLine("Time elapsed without try-catch:- " + sw.ElapsedTicks);
            Console.ReadLine();
        }
    }

This is the output of above program.


We see that when we are using exception handling it takes much more time than without exception.

Conclusion:-

In this article we have seen how performance is impacted when we use exception handling mechanism to validate user input. Recommendation is “Do not throw exception in time of input validation”.

 

Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)