Tuesday, July 10, 2012

C# Try catch .



n  If you need handling errors in your program use try/catch block .
n   try/catch block can control the errors without exit program .
n  try/catch block consists of two part
o   Try Block : put all your code in this block .
o   Catch Block : write code that will handling the error when it's occurred .
§  you can use type of Catch to control specific error.
·         ArithmeticException : this catch specialized in numerical errors
·         IndexOutOfRangeException : this catch specialized errors that occurred when an index is outside the boundary of an array .
§  You can have multi catch in your code each one specialized in specific error . in this case one block of catch can be occurred .
Example 1:
        public void action()
        {
            try
            {
                int x = 5;
                int y = 0;
                int z = x / y;
            }
            catch
            {
                Console.WriteLine("an error occurred");
            }

        }

or
            try
            {
                int x = 5;
                int y = 0;
                int z = x / y;
            }
            catch(ArithmeticException ex)
            {
                Console.WriteLine("your error is :");
                Console.WriteLine(ex.Message);
            }

Example 2 :
            try
            {
                int[] x = new int[2];
                x[0] = 85;
                x[1] = 44;
                x[2] = 33;
                Console.WriteLine(x[2]);

            }
            catch(IndexOutOfRangeException e)
            {
                Console.WriteLine("your error is :");
                Console.WriteLine(e.Message);
            }


Example 3 :
 public void action()
        {
            try
            {
                // write your code here
            }
            catch (IndexOutOfRangeException  err)
            {
                Console.WriteLine("your error is :");
                Console.WriteLine(err.Message);
            }
            catch (ArithmeticException ex)
            {
                Console.WriteLine("your error is :");
                Console.WriteLine(ex.Message);
            }
            catch
            {
                Console.WriteLine("an error occurred");
            }
        }